blob: ecd05c245d7d8c7e0e4f750ae7e19976391d6901 [file] [log] [blame]
Chris Lattner1314b992007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner1314b992007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
Chris Lattner1314b992007-04-22 06:23:29 +00009
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000010#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000011#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/SmallVector.h"
David Majnemer3087b222015-01-20 05:58:07 +000013#include "llvm/ADT/Triple.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000014#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000015#include "llvm/Bitcode/LLVMBitCodes.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000016#include "llvm/Bitcode/ReaderWriter.h"
Chandler Carruth91065212014-03-05 10:34:14 +000017#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Constants.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000019#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000020#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DerivedTypes.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000022#include "llvm/IR/DiagnosticPrinter.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000023#include "llvm/IR/GVMaterializer.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/OperandTraits.h"
30#include "llvm/IR/Operator.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000031#include "llvm/IR/ValueHandle.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000032#include "llvm/Support/CommandLine.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000033#include "llvm/Support/DataStream.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000034#include "llvm/Support/Debug.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000036#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000037#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000038#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000039#include <deque>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000040
Chris Lattner1314b992007-04-22 06:23:29 +000041using namespace llvm;
42
Teresa Johnson916495d2016-04-04 18:52:58 +000043static cl::opt<bool> PrintSummaryGUIDs(
44 "print-summary-global-ids", cl::init(false), cl::Hidden,
45 cl::desc(
46 "Print the global id for each value when reading the module summary"));
47
Benjamin Kramercced8be2015-03-17 20:40:24 +000048namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000049enum {
50 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
51};
52
Benjamin Kramercced8be2015-03-17 20:40:24 +000053class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
55
Rafael Espindolacbdcb502015-06-15 20:55:37 +000056 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000059 /// ResolveConstantForwardRefs for more information about this.
60 ///
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
65 LLVMContext &Context;
66public:
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
70 }
71
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000075 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000076
77 void clear() {
78 assert(ResolveConstants.empty() && "Constants not resolved?");
79 ValuePtrs.clear();
80 }
81
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
84 return ValuePtrs[i];
85 }
86
87 Value *back() const { return ValuePtrs.back(); }
Duncan P. N. Exon Smith7457ecb2016-03-30 04:21:52 +000088 void pop_back() { ValuePtrs.pop_back(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000089 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
92 ValuePtrs.resize(N);
93 }
94
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +000096 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +000097
David Majnemer8a1c45d2015-12-12 05:38:55 +000098 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +000099
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000100 /// Once all constants are read, this method bulk resolves any forward
101 /// references.
102 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000103};
104
Teresa Johnson61b406e2015-12-29 23:00:22 +0000105class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000106 unsigned NumFwdRefs;
107 bool AnyFwdRefs;
108 unsigned MinFwdRef;
109 unsigned MaxFwdRef;
Duncan P. N. Exon Smith3c406c22016-04-20 20:14:09 +0000110
111 /// Array of metadata references.
112 ///
113 /// Don't use std::vector here. Some versions of libc++ copy (instead of
114 /// move) on resize, and TrackingMDRef is very expensive to copy.
115 SmallVector<TrackingMDRef, 1> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000116
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000117 /// Structures for resolving old type refs.
118 struct {
119 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
120 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
121 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
122 std::vector<std::pair<TrackingMDRef, TempMDTuple>> Arrays;
123 } OldTypeRefs;
124
Benjamin Kramercced8be2015-03-17 20:40:24 +0000125 LLVMContext &Context;
126public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000127 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000128 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000129
130 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000131 unsigned size() const { return MetadataPtrs.size(); }
132 void resize(unsigned N) { MetadataPtrs.resize(N); }
133 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
134 void clear() { MetadataPtrs.clear(); }
135 Metadata *back() const { return MetadataPtrs.back(); }
136 void pop_back() { MetadataPtrs.pop_back(); }
137 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000138
139 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000140 assert(i < MetadataPtrs.size());
141 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000142 }
143
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000144 Metadata *lookup(unsigned I) const {
Duncan P. N. Exon Smithe9f85c42016-04-23 04:23:57 +0000145 if (I < MetadataPtrs.size())
146 return MetadataPtrs[I];
147 return nullptr;
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000148 }
149
Benjamin Kramercced8be2015-03-17 20:40:24 +0000150 void shrinkTo(unsigned N) {
151 assert(N <= size() && "Invalid shrinkTo request!");
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000152 assert(!AnyFwdRefs && "Unexpected forward refs");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000153 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000154 }
155
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000156 /// Return the given metadata, creating a replaceable forward reference if
157 /// necessary.
Justin Bognerae341c62016-03-17 20:12:06 +0000158 Metadata *getMetadataFwdRef(unsigned Idx);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000159
160 /// Return the the given metadata only if it is fully resolved.
161 ///
162 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
163 /// would give \c false.
164 Metadata *getMetadataIfResolved(unsigned Idx);
165
Justin Bognerae341c62016-03-17 20:12:06 +0000166 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000167 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000168 void tryToResolveCycles();
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000169 bool hasFwdRefs() const { return AnyFwdRefs; }
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000170
171 /// Upgrade a type that had an MDString reference.
172 void addTypeRef(MDString &UUID, DICompositeType &CT);
173
174 /// Upgrade a type that had an MDString reference.
175 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
176
177 /// Upgrade a type ref array that may have MDString references.
178 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
179
180private:
181 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000182};
183
184class BitcodeReader : public GVMaterializer {
185 LLVMContext &Context;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000186 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000187 std::unique_ptr<MemoryBuffer> Buffer;
188 std::unique_ptr<BitstreamReader> StreamFile;
189 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000190 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000191 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000192 // Last function offset found in the VST.
193 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000194 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000195 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000196 // Contains an arbitrary and optional string identifying the bitcode producer
197 std::string ProducerIdentification;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000198
199 std::vector<Type*> TypeList;
200 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000201 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000202 std::vector<Comdat *> ComdatList;
203 SmallVector<Instruction *, 64> InstructionList;
204
205 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000206 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000207 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
208 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000209 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000210
211 SmallVector<Instruction*, 64> InstsWithTBAATag;
212
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +0000213 bool HasSeenOldLoopTags = false;
214
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000215 /// The set of attributes by index. Index zero in the file is for null, and
216 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000217 std::vector<AttributeSet> MAttributes;
218
Karl Schimpf36440082015-08-31 16:43:55 +0000219 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000220 std::map<unsigned, AttributeSet> MAttributeGroups;
221
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000222 /// While parsing a function body, this is a list of the basic blocks for the
223 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000224 std::vector<BasicBlock*> FunctionBBs;
225
226 // When reading the module header, this list is populated with functions that
227 // have bodies later in the file.
228 std::vector<Function*> FunctionsWithBodies;
229
230 // When intrinsic functions are encountered which require upgrading they are
231 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000232 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000233 UpgradedIntrinsicMap UpgradedIntrinsics;
234
235 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
236 DenseMap<unsigned, unsigned> MDKindMap;
237
238 // Several operations happen after the module header has been read, but
239 // before function bodies are processed. This keeps track of whether
240 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000241 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000242
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000243 /// When function bodies are initially scanned, this map contains info about
244 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000245 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
246
247 /// When Metadata block is initially scanned when parsing the module, we may
248 /// choose to defer parsing of the metadata. This vector contains info about
249 /// which Metadata blocks are deferred.
250 std::vector<uint64_t> DeferredMetadataInfo;
251
252 /// These are basic blocks forward-referenced by block addresses. They are
253 /// inserted lazily into functions when they're loaded. The basic block ID is
254 /// its index into the vector.
255 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
256 std::deque<Function *> BasicBlockFwdRefQueue;
257
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000258 /// Indicates that we are using a new encoding for instruction operands where
259 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
260 /// instruction number, for a more compact encoding. Some instruction
261 /// operands are not relative to the instruction ID: basic block numbers, and
262 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000263 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000264 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000265
266 /// True if all functions will be materialized, negating the need to process
267 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000268 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000269
Benjamin Kramercced8be2015-03-17 20:40:24 +0000270 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000271 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000272
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000273 bool StripDebugInfo = false;
274
Peter Collingbourned4bff302015-11-05 22:03:56 +0000275 /// Functions that need to be matched with subprograms when upgrading old
276 /// metadata.
277 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
278
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000279 std::vector<std::string> BundleTags;
280
Benjamin Kramercced8be2015-03-17 20:40:24 +0000281public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000282 std::error_code error(BitcodeError E, const Twine &Message);
283 std::error_code error(BitcodeError E);
284 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000285
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000286 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
287 BitcodeReader(LLVMContext &Context);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000288 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000289
290 std::error_code materializeForwardReferencedFunctions();
291
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000292 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000293
294 void releaseBuffer();
295
Benjamin Kramercced8be2015-03-17 20:40:24 +0000296 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000297 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000298 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000299
Rafael Espindola6ace6852015-06-15 21:02:49 +0000300 /// \brief Main interface to parsing a bitcode buffer.
301 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000302 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
303 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000304 bool ShouldLazyLoadMetadata = false);
305
Rafael Espindola6ace6852015-06-15 21:02:49 +0000306 /// \brief Cheap mechanism to just extract module triple
307 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000308 ErrorOr<std::string> parseTriple();
309
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000310 /// Cheap mechanism to just extract the identification block out of bitcode.
311 ErrorOr<std::string> parseIdentificationBlock();
312
Benjamin Kramercced8be2015-03-17 20:40:24 +0000313 static uint64_t decodeSignRotatedValue(uint64_t V);
314
315 /// Materialize any deferred Metadata block.
316 std::error_code materializeMetadata() override;
317
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000318 void setStripDebugInfo() override;
319
Benjamin Kramercced8be2015-03-17 20:40:24 +0000320private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000321 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
322 // ProducerIdentification data member, and do some basic enforcement on the
323 // "epoch" encoded in the bitcode.
324 std::error_code parseBitcodeVersion();
325
Benjamin Kramercced8be2015-03-17 20:40:24 +0000326 std::vector<StructType *> IdentifiedStructTypes;
327 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
328 StructType *createIdentifiedStructType(LLVMContext &Context);
329
330 Type *getTypeByID(unsigned ID);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000331 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000332 if (Ty && Ty->isMetadataTy())
333 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000334 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000335 }
336 Metadata *getFnMetadataByID(unsigned ID) {
Justin Bognerae341c62016-03-17 20:12:06 +0000337 return MetadataList.getMetadataFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000338 }
339 BasicBlock *getBasicBlock(unsigned ID) const {
340 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
341 return FunctionBBs[ID];
342 }
343 AttributeSet getAttributes(unsigned i) const {
344 if (i-1 < MAttributes.size())
345 return MAttributes[i-1];
346 return AttributeSet();
347 }
348
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000349 /// Read a value/type pair out of the specified record from slot 'Slot'.
350 /// Increment Slot past the number of slots used in the record. Return true on
351 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000352 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
353 unsigned InstNum, Value *&ResVal) {
354 if (Slot == Record.size()) return true;
355 unsigned ValNo = (unsigned)Record[Slot++];
356 // Adjust the ValNo, if it was encoded relative to the InstNum.
357 if (UseRelativeIDs)
358 ValNo = InstNum - ValNo;
359 if (ValNo < InstNum) {
360 // If this is not a forward reference, just return the value we already
361 // have.
362 ResVal = getFnValueByID(ValNo, nullptr);
363 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000364 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000365 if (Slot == Record.size())
366 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000367
368 unsigned TypeNo = (unsigned)Record[Slot++];
369 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
370 return ResVal == nullptr;
371 }
372
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000373 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
374 /// past the number of slots used by the value in the record. Return true if
375 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000376 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000377 unsigned InstNum, Type *Ty, Value *&ResVal) {
378 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000379 return true;
380 // All values currently take a single record slot.
381 ++Slot;
382 return false;
383 }
384
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000385 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000386 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000387 unsigned InstNum, Type *Ty, Value *&ResVal) {
388 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000389 return ResVal == nullptr;
390 }
391
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000392 /// Version of getValue that returns ResVal directly, or 0 if there is an
393 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000394 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000395 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000396 if (Slot == Record.size()) return nullptr;
397 unsigned ValNo = (unsigned)Record[Slot];
398 // Adjust the ValNo, if it was encoded relative to the InstNum.
399 if (UseRelativeIDs)
400 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000401 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000402 }
403
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000404 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000405 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000406 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000407 if (Slot == Record.size()) return nullptr;
408 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
409 // Adjust the ValNo, if it was encoded relative to the InstNum.
410 if (UseRelativeIDs)
411 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000412 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000413 }
414
415 /// Converts alignment exponent (i.e. power of two (or zero)) to the
416 /// corresponding alignment to use. If alignment is too large, returns
417 /// a corresponding error code.
418 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000419 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000420 std::error_code parseModule(uint64_t ResumeBit,
421 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000422 std::error_code parseAttributeBlock();
423 std::error_code parseAttributeGroupBlock();
424 std::error_code parseTypeTable();
425 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000426 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000427
Teresa Johnsonff642b92015-09-17 20:12:00 +0000428 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
429 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000430 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000431 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000432 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000433 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000434 /// Save the positions of the Metadata blocks and skip parsing the blocks.
435 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000436 std::error_code parseFunctionBody(Function *F);
437 std::error_code globalCleanup();
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000438 std::error_code resolveGlobalAndIndirectSymbolInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000439 std::error_code parseMetadata(bool ModuleLevel = false);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000440 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
441 StringRef Blob,
442 unsigned &NextMetadataNo);
Teresa Johnson12545072015-11-15 02:00:09 +0000443 std::error_code parseMetadataKinds();
444 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000445 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000446 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000447 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000448 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000449 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000450 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000451 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000452 Function *F,
453 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
454};
Teresa Johnson403a7872015-10-04 14:33:43 +0000455
456/// Class to manage reading and parsing function summary index bitcode
457/// files/sections.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000458class ModuleSummaryIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000459 DiagnosticHandlerFunction DiagnosticHandler;
460
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000461 /// Eventually points to the module index built during parsing.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000462 ModuleSummaryIndex *TheIndex = nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000463
464 std::unique_ptr<MemoryBuffer> Buffer;
465 std::unique_ptr<BitstreamReader> StreamFile;
466 BitstreamCursor Stream;
467
Teresa Johnson403a7872015-10-04 14:33:43 +0000468 /// Used to indicate whether caller only wants to check for the presence
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000469 /// of the global value summary bitcode section. All blocks are skipped,
470 /// but the SeenGlobalValSummary boolean is set.
471 bool CheckGlobalValSummaryPresenceOnly = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000472
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000473 /// Indicates whether we have encountered a global value summary section
474 /// yet during parsing, used when checking if file contains global value
Teresa Johnson403a7872015-10-04 14:33:43 +0000475 /// summary section.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000476 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000477
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000478 /// Indicates whether we have already parsed the VST, used for error checking.
479 bool SeenValueSymbolTable = false;
480
481 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
482 /// Used to enable on-demand parsing of the VST.
483 uint64_t VSTOffset = 0;
484
485 // Map to save ValueId to GUID association that was recorded in the
486 // ValueSymbolTable. It is used after the VST is parsed to convert
487 // call graph edges read from the function summary from referencing
488 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000489 // they are recorded in the summary index being built.
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000490 DenseMap<unsigned, GlobalValue::GUID> ValueIdToCallGraphGUIDMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000491
492 /// Map to save the association between summary offset in the VST to the
493 /// GlobalValueInfo object created when parsing it. Used to access the
494 /// info object when parsing the summary section.
495 DenseMap<uint64_t, GlobalValueInfo *> SummaryOffsetToInfoMap;
Teresa Johnson403a7872015-10-04 14:33:43 +0000496
497 /// Map populated during module path string table parsing, from the
498 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000499 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000500 /// summary records.
501 DenseMap<uint64_t, StringRef> ModuleIdMap;
502
Teresa Johnsone1164de2016-02-10 21:55:02 +0000503 /// Original source file name recorded in a bitcode record.
504 std::string SourceFileName;
505
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000506public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000507 std::error_code error(BitcodeError E, const Twine &Message);
508 std::error_code error(BitcodeError E);
509 std::error_code error(const Twine &Message);
510
Teresa Johnson26ab5772016-03-15 00:04:37 +0000511 ModuleSummaryIndexBitcodeReader(
512 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000513 bool CheckGlobalValSummaryPresenceOnly = false);
Teresa Johnson26ab5772016-03-15 00:04:37 +0000514 ModuleSummaryIndexBitcodeReader(
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000515 DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000516 bool CheckGlobalValSummaryPresenceOnly = false);
517 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
Teresa Johnson403a7872015-10-04 14:33:43 +0000518
519 void freeState();
520
521 void releaseBuffer();
522
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000523 /// Check if the parser has encountered a summary section.
524 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
Teresa Johnson403a7872015-10-04 14:33:43 +0000525
526 /// \brief Main interface to parsing a bitcode buffer.
527 /// \returns true if an error occurred.
528 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000529 ModuleSummaryIndex *I);
Teresa Johnson403a7872015-10-04 14:33:43 +0000530
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000531 /// \brief Interface for parsing a summary lazily.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000532 std::error_code
533 parseGlobalValueSummary(std::unique_ptr<DataStreamer> Streamer,
534 ModuleSummaryIndex *I, size_t SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000535
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000536private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000537 std::error_code parseModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000538 std::error_code parseValueSymbolTable(
539 uint64_t Offset,
540 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Teresa Johnson403a7872015-10-04 14:33:43 +0000541 std::error_code parseEntireSummary();
542 std::error_code parseModuleStringTable();
543 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
544 std::error_code initStreamFromBuffer();
545 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000546 GlobalValue::GUID getGUIDFromValueId(unsigned ValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000547 GlobalValueInfo *getInfoFromSummaryOffset(uint64_t Offset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000548};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000549} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000550
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000551BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
552 DiagnosticSeverity Severity,
553 const Twine &Msg)
554 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
555
556void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
557
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000558static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000559 std::error_code EC, const Twine &Message) {
560 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
561 DiagnosticHandler(DI);
562 return EC;
563}
564
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000565static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000566 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000567 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000568}
569
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000570static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000571 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000572 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
573 Message);
574}
575
576static std::error_code error(LLVMContext &Context, std::error_code EC) {
577 return error(Context, EC, EC.message());
578}
579
580static std::error_code error(LLVMContext &Context, const Twine &Message) {
581 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
582 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000583}
584
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000585std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000586 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000587 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000588 Message + " (Producer: '" + ProducerIdentification +
589 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000590 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000591 return ::error(Context, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000592}
593
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000594std::error_code BitcodeReader::error(const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000595 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000596 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000597 Message + " (Producer: '" + ProducerIdentification +
598 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000599 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000600 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
601 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000602}
603
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000604std::error_code BitcodeReader::error(BitcodeError E) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000605 return ::error(Context, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000606}
607
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000608BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
609 : Context(Context), Buffer(Buffer), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000610 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000611
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000612BitcodeReader::BitcodeReader(LLVMContext &Context)
613 : Context(Context), Buffer(nullptr), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000614 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000615
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000616std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
617 if (WillMaterializeAllForwardRefs)
618 return std::error_code();
619
620 // Prevent recursion.
621 WillMaterializeAllForwardRefs = true;
622
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000623 while (!BasicBlockFwdRefQueue.empty()) {
624 Function *F = BasicBlockFwdRefQueue.front();
625 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000626 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000627 if (!BasicBlockFwdRefs.count(F))
628 // Already materialized.
629 continue;
630
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000631 // Check for a function that isn't materializable to prevent an infinite
632 // loop. When parsing a blockaddress stored in a global variable, there
633 // isn't a trivial way to check if a function will have a body without a
634 // linear search through FunctionsWithBodies, so just check it here.
635 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000636 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000637
638 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000639 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000640 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000641 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000642 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000643
644 // Reset state.
645 WillMaterializeAllForwardRefs = false;
646 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000647}
648
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000649void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000650 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000651 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000652 ValueList.clear();
Teresa Johnson61b406e2015-12-29 23:00:22 +0000653 MetadataList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000654 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000655
Bill Wendlinge94d8432012-12-07 23:16:57 +0000656 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000657 std::vector<BasicBlock*>().swap(FunctionBBs);
658 std::vector<Function*>().swap(FunctionsWithBodies);
659 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000660 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000661 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000662
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000663 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000664 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000665}
666
Chris Lattnerfee5a372007-05-04 03:30:17 +0000667//===----------------------------------------------------------------------===//
668// Helper functions to implement forward reference resolution, etc.
669//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000670
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000671/// Convert a string from a record into an std::string, return true on failure.
672template <typename StrTy>
673static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000674 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000675 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000676 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000677
Chris Lattnere14cb882007-05-04 19:11:41 +0000678 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
679 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000680 return false;
681}
682
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000683static bool hasImplicitComdat(size_t Val) {
684 switch (Val) {
685 default:
686 return false;
687 case 1: // Old WeakAnyLinkage
688 case 4: // Old LinkOnceAnyLinkage
689 case 10: // Old WeakODRLinkage
690 case 11: // Old LinkOnceODRLinkage
691 return true;
692 }
693}
694
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000695static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000696 switch (Val) {
697 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000698 case 0:
699 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000700 case 2:
701 return GlobalValue::AppendingLinkage;
702 case 3:
703 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000704 case 5:
705 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
706 case 6:
707 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
708 case 7:
709 return GlobalValue::ExternalWeakLinkage;
710 case 8:
711 return GlobalValue::CommonLinkage;
712 case 9:
713 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000714 case 12:
715 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000716 case 13:
717 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
718 case 14:
719 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000720 case 15:
721 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000722 case 1: // Old value with implicit comdat.
723 case 16:
724 return GlobalValue::WeakAnyLinkage;
725 case 10: // Old value with implicit comdat.
726 case 17:
727 return GlobalValue::WeakODRLinkage;
728 case 4: // Old value with implicit comdat.
729 case 18:
730 return GlobalValue::LinkOnceAnyLinkage;
731 case 11: // Old value with implicit comdat.
732 case 19:
733 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000734 }
735}
736
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000737static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000738 switch (Val) {
739 default: // Map unknown visibilities to default.
740 case 0: return GlobalValue::DefaultVisibility;
741 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000742 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000743 }
744}
745
Nico Rieck7157bb72014-01-14 15:22:47 +0000746static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000747getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000748 switch (Val) {
749 default: // Map unknown values to default.
750 case 0: return GlobalValue::DefaultStorageClass;
751 case 1: return GlobalValue::DLLImportStorageClass;
752 case 2: return GlobalValue::DLLExportStorageClass;
753 }
754}
755
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000756static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000757 switch (Val) {
758 case 0: return GlobalVariable::NotThreadLocal;
759 default: // Map unknown non-zero value to general dynamic.
760 case 1: return GlobalVariable::GeneralDynamicTLSModel;
761 case 2: return GlobalVariable::LocalDynamicTLSModel;
762 case 3: return GlobalVariable::InitialExecTLSModel;
763 case 4: return GlobalVariable::LocalExecTLSModel;
764 }
765}
766
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000767static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000768 switch (Val) {
769 default: return -1;
770 case bitc::CAST_TRUNC : return Instruction::Trunc;
771 case bitc::CAST_ZEXT : return Instruction::ZExt;
772 case bitc::CAST_SEXT : return Instruction::SExt;
773 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
774 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
775 case bitc::CAST_UITOFP : return Instruction::UIToFP;
776 case bitc::CAST_SITOFP : return Instruction::SIToFP;
777 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
778 case bitc::CAST_FPEXT : return Instruction::FPExt;
779 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
780 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
781 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000782 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000783 }
784}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000785
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000786static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000787 bool IsFP = Ty->isFPOrFPVectorTy();
788 // BinOps are only valid for int/fp or vector of int/fp types
789 if (!IsFP && !Ty->isIntOrIntVectorTy())
790 return -1;
791
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000792 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000793 default:
794 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000795 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000796 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000797 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000798 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000799 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000800 return IsFP ? Instruction::FMul : Instruction::Mul;
801 case bitc::BINOP_UDIV:
802 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000803 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000804 return IsFP ? Instruction::FDiv : Instruction::SDiv;
805 case bitc::BINOP_UREM:
806 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000807 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000808 return IsFP ? Instruction::FRem : Instruction::SRem;
809 case bitc::BINOP_SHL:
810 return IsFP ? -1 : Instruction::Shl;
811 case bitc::BINOP_LSHR:
812 return IsFP ? -1 : Instruction::LShr;
813 case bitc::BINOP_ASHR:
814 return IsFP ? -1 : Instruction::AShr;
815 case bitc::BINOP_AND:
816 return IsFP ? -1 : Instruction::And;
817 case bitc::BINOP_OR:
818 return IsFP ? -1 : Instruction::Or;
819 case bitc::BINOP_XOR:
820 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000821 }
822}
823
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000824static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000825 switch (Val) {
826 default: return AtomicRMWInst::BAD_BINOP;
827 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
828 case bitc::RMW_ADD: return AtomicRMWInst::Add;
829 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
830 case bitc::RMW_AND: return AtomicRMWInst::And;
831 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
832 case bitc::RMW_OR: return AtomicRMWInst::Or;
833 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
834 case bitc::RMW_MAX: return AtomicRMWInst::Max;
835 case bitc::RMW_MIN: return AtomicRMWInst::Min;
836 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
837 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
838 }
839}
840
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000841static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000842 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +0000843 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
844 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
845 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
846 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
847 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
848 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000849 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +0000850 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000851 }
852}
853
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000854static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000855 switch (Val) {
856 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
857 default: // Map unknown scopes to cross-thread.
858 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
859 }
860}
861
David Majnemerdad0a642014-06-27 18:19:56 +0000862static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
863 switch (Val) {
864 default: // Map unknown selection kinds to any.
865 case bitc::COMDAT_SELECTION_KIND_ANY:
866 return Comdat::Any;
867 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
868 return Comdat::ExactMatch;
869 case bitc::COMDAT_SELECTION_KIND_LARGEST:
870 return Comdat::Largest;
871 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
872 return Comdat::NoDuplicates;
873 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
874 return Comdat::SameSize;
875 }
876}
877
James Molloy88eb5352015-07-10 12:52:00 +0000878static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
879 FastMathFlags FMF;
880 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
881 FMF.setUnsafeAlgebra();
882 if (0 != (Val & FastMathFlags::NoNaNs))
883 FMF.setNoNaNs();
884 if (0 != (Val & FastMathFlags::NoInfs))
885 FMF.setNoInfs();
886 if (0 != (Val & FastMathFlags::NoSignedZeros))
887 FMF.setNoSignedZeros();
888 if (0 != (Val & FastMathFlags::AllowReciprocal))
889 FMF.setAllowReciprocal();
890 return FMF;
891}
892
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000893static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000894 switch (Val) {
895 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
896 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
897 }
898}
899
Gabor Greiff6caff662008-05-10 08:32:32 +0000900namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000901namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000902/// \brief A class for maintaining the slot number definition
903/// as a placeholder for the actual definition for forward constants defs.
904class ConstantPlaceHolder : public ConstantExpr {
905 void operator=(const ConstantPlaceHolder &) = delete;
906
907public:
908 // allocate space for exactly one operand
909 void *operator new(size_t s) { return User::operator new(s, 1); }
910 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000911 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000912 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
913 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000914
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000915 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
916 static bool classof(const Value *V) {
917 return isa<ConstantExpr>(V) &&
918 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
919 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000920
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000921 /// Provide fast operand accessors
922 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
923};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000924} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000925
Chris Lattner2d8cd802009-03-31 22:55:09 +0000926// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000927template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000928struct OperandTraits<ConstantPlaceHolder> :
929 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000930};
Richard Trieue3d126c2014-11-21 02:42:08 +0000931DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000932} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000933
David Majnemer8a1c45d2015-12-12 05:38:55 +0000934void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000935 if (Idx == size()) {
936 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000937 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000938 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000939
Chris Lattner2d8cd802009-03-31 22:55:09 +0000940 if (Idx >= size())
941 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000942
Chris Lattner2d8cd802009-03-31 22:55:09 +0000943 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000944 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000945 OldV = V;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000946 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000947 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000948
Chris Lattner2d8cd802009-03-31 22:55:09 +0000949 // Handle constants and non-constants (e.g. instrs) differently for
950 // efficiency.
951 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
952 ResolveConstants.push_back(std::make_pair(PHC, Idx));
953 OldV = V;
954 } else {
955 // If there was a forward reference to this value, replace it.
956 Value *PrevVal = OldV;
957 OldV->replaceAllUsesWith(V);
958 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000959 }
960}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000961
Chris Lattner1663cca2007-04-24 05:48:56 +0000962Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000963 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000964 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000965 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000966
Chris Lattner2d8cd802009-03-31 22:55:09 +0000967 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000968 if (Ty != V->getType())
969 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000970 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000971 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000972
973 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000974 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000975 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000976 return C;
977}
978
David Majnemer8a1c45d2015-12-12 05:38:55 +0000979Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000980 // Bail out for a clearly invalid value. This would make us call resize(0)
981 if (Idx == UINT_MAX)
982 return nullptr;
983
Chris Lattner2d8cd802009-03-31 22:55:09 +0000984 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000985 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000986
Chris Lattner2d8cd802009-03-31 22:55:09 +0000987 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000988 // If the types don't match, it's invalid.
989 if (Ty && Ty != V->getType())
990 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000991 return V;
Chris Lattner83930552007-05-01 07:01:57 +0000992 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000993
Chris Lattner1fc27f02007-05-02 05:16:49 +0000994 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000995 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000996
Chris Lattner83930552007-05-01 07:01:57 +0000997 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000998 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000999 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +00001000 return V;
1001}
1002
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001003/// Once all constants are read, this method bulk resolves any forward
1004/// references. The idea behind this is that we sometimes get constants (such
1005/// as large arrays) which reference *many* forward ref constants. Replacing
1006/// each of these causes a lot of thrashing when building/reuniquing the
1007/// constant. Instead of doing this, we look at all the uses and rewrite all
1008/// the place holders at once for any constant that uses a placeholder.
1009void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001010 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +00001011 // binary search.
1012 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001013
Chris Lattner74429932008-08-21 02:34:16 +00001014 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001015
Chris Lattner74429932008-08-21 02:34:16 +00001016 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +00001017 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +00001018 Constant *Placeholder = ResolveConstants.back().first;
1019 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001020
Chris Lattner74429932008-08-21 02:34:16 +00001021 // Loop over all users of the placeholder, updating them to reference the
1022 // new value. If they reference more than one placeholder, update them all
1023 // at once.
1024 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001025 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +00001026 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001027
Chris Lattner74429932008-08-21 02:34:16 +00001028 // If the using object isn't uniqued, just update the operands. This
1029 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001030 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +00001031 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001032 continue;
1033 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001034
Chris Lattner74429932008-08-21 02:34:16 +00001035 // Otherwise, we have a constant that uses the placeholder. Replace that
1036 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001037 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +00001038 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1039 I != E; ++I) {
1040 Value *NewOp;
1041 if (!isa<ConstantPlaceHolder>(*I)) {
1042 // Not a placeholder reference.
1043 NewOp = *I;
1044 } else if (*I == Placeholder) {
1045 // Common case is that it just references this one placeholder.
1046 NewOp = RealVal;
1047 } else {
1048 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001049 ResolveConstantsTy::iterator It =
1050 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001051 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1052 0));
1053 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001054 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001055 }
1056
1057 NewOps.push_back(cast<Constant>(NewOp));
1058 }
1059
1060 // Make the new constant.
1061 Constant *NewC;
1062 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001063 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001064 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001065 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001066 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001067 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001068 } else {
1069 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001070 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001071 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001072
Chris Lattner74429932008-08-21 02:34:16 +00001073 UserC->replaceAllUsesWith(NewC);
1074 UserC->destroyConstant();
1075 NewOps.clear();
1076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001077
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001078 // Update all ValueHandles, they should be the only users at this point.
1079 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001080 delete Placeholder;
1081 }
1082}
1083
Teresa Johnson61b406e2015-12-29 23:00:22 +00001084void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001085 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001086 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001087 return;
1088 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001089
Devang Patel05eb6172009-08-04 06:00:18 +00001090 if (Idx >= size())
1091 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001092
Teresa Johnson61b406e2015-12-29 23:00:22 +00001093 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001094 if (!OldMD) {
1095 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001096 return;
1097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001098
Devang Patel05eb6172009-08-04 06:00:18 +00001099 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001100 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001101 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001102 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001103}
1104
Justin Bognerae341c62016-03-17 20:12:06 +00001105Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001106 if (Idx >= size())
1107 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001108
Teresa Johnson61b406e2015-12-29 23:00:22 +00001109 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001110 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001111
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001112 // Track forward refs to be resolved later.
1113 if (AnyFwdRefs) {
1114 MinFwdRef = std::min(MinFwdRef, Idx);
1115 MaxFwdRef = std::max(MaxFwdRef, Idx);
1116 } else {
1117 AnyFwdRefs = true;
1118 MinFwdRef = MaxFwdRef = Idx;
1119 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001120 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001121
1122 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001123 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001124 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001125 return MD;
1126}
1127
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00001128Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
1129 Metadata *MD = lookup(Idx);
1130 if (auto *N = dyn_cast_or_null<MDNode>(MD))
1131 if (!N->isResolved())
1132 return nullptr;
1133 return MD;
1134}
1135
Justin Bognerae341c62016-03-17 20:12:06 +00001136MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1137 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1138}
1139
Teresa Johnson61b406e2015-12-29 23:00:22 +00001140void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001141 if (NumFwdRefs)
1142 // Still forward references... can't resolve cycles.
1143 return;
1144
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001145 // Give up on finding a full definition for any forward decls that remain.
1146 for (const auto &Ref : OldTypeRefs.FwdDecls)
1147 OldTypeRefs.Final.insert(Ref);
1148 OldTypeRefs.FwdDecls.clear();
1149
1150 // Upgrade from old type ref arrays. In strange cases, this could add to
1151 // OldTypeRefs.Unknown.
1152 for (const auto &Array : OldTypeRefs.Arrays)
1153 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
1154
1155 // Replace old string-based type refs with the resolved node, if possible.
1156 // If we haven't seen the node, leave it to the verifier to complain about
1157 // the invalid string reference.
1158 for (const auto &Ref : OldTypeRefs.Unknown)
1159 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
1160 Ref.second->replaceAllUsesWith(CT);
1161 else
1162 Ref.second->replaceAllUsesWith(Ref.first);
1163 OldTypeRefs.Unknown.clear();
1164
1165 if (!AnyFwdRefs)
1166 // Nothing to do.
1167 return;
1168
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001169 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001170 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001171 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001172 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001173 if (!N)
1174 continue;
1175
1176 assert(!N->isTemporary() && "Unexpected forward reference");
1177 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001178 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001179
1180 // Make sure we return early again until there's another forward ref.
1181 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001182}
Chris Lattner1314b992007-04-22 06:23:29 +00001183
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001184void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
1185 DICompositeType &CT) {
1186 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
1187 if (CT.isForwardDecl())
1188 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
1189 else
1190 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
1191}
1192
1193Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
1194 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
1195 if (LLVM_LIKELY(!UUID))
1196 return MaybeUUID;
1197
1198 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
1199 return CT;
1200
1201 auto &Ref = OldTypeRefs.Unknown[UUID];
1202 if (!Ref)
1203 Ref = MDNode::getTemporary(Context, None);
1204 return Ref.get();
1205}
1206
1207Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
1208 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1209 if (!Tuple || Tuple->isDistinct())
1210 return MaybeTuple;
1211
1212 // Look through the array immediately if possible.
1213 if (!Tuple->isTemporary())
1214 return resolveTypeRefArray(Tuple);
1215
1216 // Create and return a placeholder to use for now. Eventually
1217 // resolveTypeRefArrays() will be resolve this forward reference.
1218 OldTypeRefs.Arrays.emplace_back(
1219 std::piecewise_construct, std::make_tuple(Tuple),
1220 std::make_tuple(MDTuple::getTemporary(Context, None)));
1221 return OldTypeRefs.Arrays.back().second.get();
1222}
1223
1224Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
1225 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1226 if (!Tuple || Tuple->isDistinct())
1227 return MaybeTuple;
1228
1229 // Look through the DITypeRefArray, upgrading each DITypeRef.
1230 SmallVector<Metadata *, 32> Ops;
1231 Ops.reserve(Tuple->getNumOperands());
1232 for (Metadata *MD : Tuple->operands())
1233 Ops.push_back(upgradeTypeRef(MD));
1234
1235 return MDTuple::get(Context, Ops);
1236}
1237
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001238Type *BitcodeReader::getTypeByID(unsigned ID) {
1239 // The type table size is always specified correctly.
1240 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001241 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001242
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001243 if (Type *Ty = TypeList[ID])
1244 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001245
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001246 // If we have a forward reference, the only possible case is when it is to a
1247 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001248 return TypeList[ID] = createIdentifiedStructType(Context);
1249}
1250
1251StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1252 StringRef Name) {
1253 auto *Ret = StructType::create(Context, Name);
1254 IdentifiedStructTypes.push_back(Ret);
1255 return Ret;
1256}
1257
1258StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1259 auto *Ret = StructType::create(Context);
1260 IdentifiedStructTypes.push_back(Ret);
1261 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001262}
1263
Chris Lattnerfee5a372007-05-04 03:30:17 +00001264//===----------------------------------------------------------------------===//
1265// Functions for parsing blocks from the bitcode file
1266//===----------------------------------------------------------------------===//
1267
Bill Wendling56aeccc2013-02-04 23:32:23 +00001268
1269/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1270/// been decoded from the given integer. This function must stay in sync with
1271/// 'encodeLLVMAttributesForBitcode'.
1272static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1273 uint64_t EncodedAttrs) {
1274 // FIXME: Remove in 4.0.
1275
1276 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1277 // the bits above 31 down by 11 bits.
1278 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1279 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1280 "Alignment must be a power of two.");
1281
1282 if (Alignment)
1283 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001284 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001285 (EncodedAttrs & 0xffff));
1286}
1287
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001288std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001289 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001290 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001291
Devang Patela05633e2008-09-26 22:53:05 +00001292 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001293 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001294
Chris Lattnerfee5a372007-05-04 03:30:17 +00001295 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001296
Bill Wendling71173cb2013-01-27 00:36:48 +00001297 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001298
Chris Lattnerfee5a372007-05-04 03:30:17 +00001299 // Read all the records.
1300 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001301 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001302
Chris Lattner27d38752013-01-20 02:13:19 +00001303 switch (Entry.Kind) {
1304 case BitstreamEntry::SubBlock: // Handled for us already.
1305 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001306 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001307 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001308 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001309 case BitstreamEntry::Record:
1310 // The interesting case.
1311 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001312 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001313
Chris Lattnerfee5a372007-05-04 03:30:17 +00001314 // Read a record.
1315 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001316 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001317 default: // Default behavior: ignore.
1318 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001319 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1320 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001321 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001322 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001323
Chris Lattnerfee5a372007-05-04 03:30:17 +00001324 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001325 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001326 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001327 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001328 }
Devang Patela05633e2008-09-26 22:53:05 +00001329
Bill Wendlinge94d8432012-12-07 23:16:57 +00001330 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001331 Attrs.clear();
1332 break;
1333 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001334 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1335 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1336 Attrs.push_back(MAttributeGroups[Record[i]]);
1337
1338 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1339 Attrs.clear();
1340 break;
1341 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001342 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001343 }
1344}
1345
Reid Klecknere9f36af2013-11-12 01:31:00 +00001346// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001347static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001348 switch (Code) {
1349 default:
1350 return Attribute::None;
1351 case bitc::ATTR_KIND_ALIGNMENT:
1352 return Attribute::Alignment;
1353 case bitc::ATTR_KIND_ALWAYS_INLINE:
1354 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001355 case bitc::ATTR_KIND_ARGMEMONLY:
1356 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001357 case bitc::ATTR_KIND_BUILTIN:
1358 return Attribute::Builtin;
1359 case bitc::ATTR_KIND_BY_VAL:
1360 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001361 case bitc::ATTR_KIND_IN_ALLOCA:
1362 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001363 case bitc::ATTR_KIND_COLD:
1364 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001365 case bitc::ATTR_KIND_CONVERGENT:
1366 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001367 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1368 return Attribute::InaccessibleMemOnly;
1369 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1370 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001371 case bitc::ATTR_KIND_INLINE_HINT:
1372 return Attribute::InlineHint;
1373 case bitc::ATTR_KIND_IN_REG:
1374 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001375 case bitc::ATTR_KIND_JUMP_TABLE:
1376 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001377 case bitc::ATTR_KIND_MIN_SIZE:
1378 return Attribute::MinSize;
1379 case bitc::ATTR_KIND_NAKED:
1380 return Attribute::Naked;
1381 case bitc::ATTR_KIND_NEST:
1382 return Attribute::Nest;
1383 case bitc::ATTR_KIND_NO_ALIAS:
1384 return Attribute::NoAlias;
1385 case bitc::ATTR_KIND_NO_BUILTIN:
1386 return Attribute::NoBuiltin;
1387 case bitc::ATTR_KIND_NO_CAPTURE:
1388 return Attribute::NoCapture;
1389 case bitc::ATTR_KIND_NO_DUPLICATE:
1390 return Attribute::NoDuplicate;
1391 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1392 return Attribute::NoImplicitFloat;
1393 case bitc::ATTR_KIND_NO_INLINE:
1394 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001395 case bitc::ATTR_KIND_NO_RECURSE:
1396 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001397 case bitc::ATTR_KIND_NON_LAZY_BIND:
1398 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001399 case bitc::ATTR_KIND_NON_NULL:
1400 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001401 case bitc::ATTR_KIND_DEREFERENCEABLE:
1402 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001403 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1404 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001405 case bitc::ATTR_KIND_ALLOC_SIZE:
1406 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001407 case bitc::ATTR_KIND_NO_RED_ZONE:
1408 return Attribute::NoRedZone;
1409 case bitc::ATTR_KIND_NO_RETURN:
1410 return Attribute::NoReturn;
1411 case bitc::ATTR_KIND_NO_UNWIND:
1412 return Attribute::NoUnwind;
1413 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1414 return Attribute::OptimizeForSize;
1415 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1416 return Attribute::OptimizeNone;
1417 case bitc::ATTR_KIND_READ_NONE:
1418 return Attribute::ReadNone;
1419 case bitc::ATTR_KIND_READ_ONLY:
1420 return Attribute::ReadOnly;
1421 case bitc::ATTR_KIND_RETURNED:
1422 return Attribute::Returned;
1423 case bitc::ATTR_KIND_RETURNS_TWICE:
1424 return Attribute::ReturnsTwice;
1425 case bitc::ATTR_KIND_S_EXT:
1426 return Attribute::SExt;
1427 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1428 return Attribute::StackAlignment;
1429 case bitc::ATTR_KIND_STACK_PROTECT:
1430 return Attribute::StackProtect;
1431 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1432 return Attribute::StackProtectReq;
1433 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1434 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001435 case bitc::ATTR_KIND_SAFESTACK:
1436 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001437 case bitc::ATTR_KIND_STRUCT_RET:
1438 return Attribute::StructRet;
1439 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1440 return Attribute::SanitizeAddress;
1441 case bitc::ATTR_KIND_SANITIZE_THREAD:
1442 return Attribute::SanitizeThread;
1443 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1444 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001445 case bitc::ATTR_KIND_SWIFT_ERROR:
1446 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001447 case bitc::ATTR_KIND_SWIFT_SELF:
1448 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001449 case bitc::ATTR_KIND_UW_TABLE:
1450 return Attribute::UWTable;
1451 case bitc::ATTR_KIND_Z_EXT:
1452 return Attribute::ZExt;
1453 }
1454}
1455
JF Bastien30bf96b2015-02-22 19:32:03 +00001456std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1457 unsigned &Alignment) {
1458 // Note: Alignment in bitcode files is incremented by 1, so that zero
1459 // can be used for default alignment.
1460 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001461 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001462 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1463 return std::error_code();
1464}
1465
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001466std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001467 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001468 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001469 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001470 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001471 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001472 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001473}
1474
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001475std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001476 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001477 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001478
1479 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001480 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001481
1482 SmallVector<uint64_t, 64> Record;
1483
1484 // Read all the records.
1485 while (1) {
1486 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1487
1488 switch (Entry.Kind) {
1489 case BitstreamEntry::SubBlock: // Handled for us already.
1490 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001491 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001492 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001493 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001494 case BitstreamEntry::Record:
1495 // The interesting case.
1496 break;
1497 }
1498
1499 // Read a record.
1500 Record.clear();
1501 switch (Stream.readRecord(Entry.ID, Record)) {
1502 default: // Default behavior: ignore.
1503 break;
1504 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1505 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001506 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001507
Bill Wendlinge46707e2013-02-11 22:32:29 +00001508 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001509 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1510
1511 AttrBuilder B;
1512 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1513 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001514 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001515 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001516 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001517
1518 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001519 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001520 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001521 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001522 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001523 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001524 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001525 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001526 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001527 else if (Kind == Attribute::Dereferenceable)
1528 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001529 else if (Kind == Attribute::DereferenceableOrNull)
1530 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001531 else if (Kind == Attribute::AllocSize)
1532 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001533 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001534 assert((Record[i] == 3 || Record[i] == 4) &&
1535 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001536 bool HasValue = (Record[i++] == 4);
1537 SmallString<64> KindStr;
1538 SmallString<64> ValStr;
1539
1540 while (Record[i] != 0 && i != e)
1541 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001542 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001543
1544 if (HasValue) {
1545 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001546 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001547 while (Record[i] != 0 && i != e)
1548 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001549 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001550 }
1551
1552 B.addAttribute(KindStr.str(), ValStr.str());
1553 }
1554 }
1555
Bill Wendlinge46707e2013-02-11 22:32:29 +00001556 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001557 break;
1558 }
1559 }
1560 }
1561}
1562
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001563std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001564 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001565 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001566
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001567 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001568}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001569
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001570std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001571 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001572 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001573
1574 SmallVector<uint64_t, 64> Record;
1575 unsigned NumRecords = 0;
1576
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001577 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001578
Chris Lattner1314b992007-04-22 06:23:29 +00001579 // Read all the records for this type table.
1580 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001581 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001582
Chris Lattner27d38752013-01-20 02:13:19 +00001583 switch (Entry.Kind) {
1584 case BitstreamEntry::SubBlock: // Handled for us already.
1585 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001586 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001587 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001588 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001589 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001590 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001591 case BitstreamEntry::Record:
1592 // The interesting case.
1593 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001594 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001595
Chris Lattner1314b992007-04-22 06:23:29 +00001596 // Read a record.
1597 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001598 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001599 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001600 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001601 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001602 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1603 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1604 // type list. This allows us to reserve space.
1605 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001606 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001607 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001608 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001609 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001610 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001611 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001612 case bitc::TYPE_CODE_HALF: // HALF
1613 ResultTy = Type::getHalfTy(Context);
1614 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001615 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001616 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001617 break;
1618 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001619 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001620 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001621 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001622 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001623 break;
1624 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001625 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001626 break;
1627 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001628 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001629 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001630 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001631 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001632 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001633 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001634 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001635 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001636 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1637 ResultTy = Type::getX86_MMXTy(Context);
1638 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001639 case bitc::TYPE_CODE_TOKEN: // TOKEN
1640 ResultTy = Type::getTokenTy(Context);
1641 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001642 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001643 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001644 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001645
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001646 uint64_t NumBits = Record[0];
1647 if (NumBits < IntegerType::MIN_INT_BITS ||
1648 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001649 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001650 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001651 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001653 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001654 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001655 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001656 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001657 unsigned AddressSpace = 0;
1658 if (Record.size() == 2)
1659 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001660 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001661 if (!ResultTy ||
1662 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001663 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001664 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001665 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001666 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001667 case bitc::TYPE_CODE_FUNCTION_OLD: {
1668 // FIXME: attrid is dead, remove it in LLVM 4.0
1669 // FUNCTION: [vararg, attrid, retty, paramty x N]
1670 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001671 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001672 SmallVector<Type*, 8> ArgTys;
1673 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1674 if (Type *T = getTypeByID(Record[i]))
1675 ArgTys.push_back(T);
1676 else
1677 break;
1678 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001679
Nuno Lopes561dae02012-05-23 15:19:39 +00001680 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001681 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001682 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001683
1684 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1685 break;
1686 }
Chad Rosier95898722011-11-03 00:14:01 +00001687 case bitc::TYPE_CODE_FUNCTION: {
1688 // FUNCTION: [vararg, retty, paramty x N]
1689 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001690 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001691 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001692 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001693 if (Type *T = getTypeByID(Record[i])) {
1694 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001695 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001696 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001697 }
Chad Rosier95898722011-11-03 00:14:01 +00001698 else
1699 break;
1700 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001701
Chad Rosier95898722011-11-03 00:14:01 +00001702 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001703 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001704 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001705
1706 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1707 break;
1708 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001709 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001710 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001711 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001712 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001713 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1714 if (Type *T = getTypeByID(Record[i]))
1715 EltTys.push_back(T);
1716 else
1717 break;
1718 }
1719 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001720 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001721 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001722 break;
1723 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001724 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001725 if (convertToString(Record, 0, TypeName))
1726 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001727 continue;
1728
1729 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1730 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001731 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001732
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001733 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001734 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001735
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001736 // Check to see if this was forward referenced, if so fill in the temp.
1737 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1738 if (Res) {
1739 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001740 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001741 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001742 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001744
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001745 SmallVector<Type*, 8> EltTys;
1746 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1747 if (Type *T = getTypeByID(Record[i]))
1748 EltTys.push_back(T);
1749 else
1750 break;
1751 }
1752 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001753 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001754 Res->setBody(EltTys, Record[0]);
1755 ResultTy = Res;
1756 break;
1757 }
1758 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1759 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001760 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761
1762 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001763 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001764
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001765 // Check to see if this was forward referenced, if so fill in the temp.
1766 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1767 if (Res) {
1768 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001769 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001770 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001771 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001772 TypeName.clear();
1773 ResultTy = Res;
1774 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001775 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001776 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1777 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001778 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001779 ResultTy = getTypeByID(Record[1]);
1780 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001781 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001782 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001783 break;
1784 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1785 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001786 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001787 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001788 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001789 ResultTy = getTypeByID(Record[1]);
1790 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001791 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001792 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793 break;
1794 }
1795
1796 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001797 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001798 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001799 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001800 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001801 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001802 TypeList[NumRecords++] = ResultTy;
1803 }
1804}
1805
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001806std::error_code BitcodeReader::parseOperandBundleTags() {
1807 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1808 return error("Invalid record");
1809
1810 if (!BundleTags.empty())
1811 return error("Invalid multiple blocks");
1812
1813 SmallVector<uint64_t, 64> Record;
1814
1815 while (1) {
1816 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1817
1818 switch (Entry.Kind) {
1819 case BitstreamEntry::SubBlock: // Handled for us already.
1820 case BitstreamEntry::Error:
1821 return error("Malformed block");
1822 case BitstreamEntry::EndBlock:
1823 return std::error_code();
1824 case BitstreamEntry::Record:
1825 // The interesting case.
1826 break;
1827 }
1828
1829 // Tags are implicitly mapped to integers by their order.
1830
1831 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1832 return error("Invalid record");
1833
1834 // OPERAND_BUNDLE_TAG: [strchr x N]
1835 BundleTags.emplace_back();
1836 if (convertToString(Record, 0, BundleTags.back()))
1837 return error("Invalid record");
1838 Record.clear();
1839 }
1840}
1841
Teresa Johnsonff642b92015-09-17 20:12:00 +00001842/// Associate a value with its name from the given index in the provided record.
1843ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1844 unsigned NameIndex, Triple &TT) {
1845 SmallString<128> ValueName;
1846 if (convertToString(Record, NameIndex, ValueName))
1847 return error("Invalid record");
1848 unsigned ValueID = Record[0];
1849 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1850 return error("Invalid record");
1851 Value *V = ValueList[ValueID];
1852
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001853 StringRef NameStr(ValueName.data(), ValueName.size());
1854 if (NameStr.find_first_of(0) != StringRef::npos)
1855 return error("Invalid value name");
1856 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001857 auto *GO = dyn_cast<GlobalObject>(V);
1858 if (GO) {
1859 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1860 if (TT.isOSBinFormatMachO())
1861 GO->setComdat(nullptr);
1862 else
1863 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1864 }
1865 }
1866 return V;
1867}
1868
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001869/// Helper to note and return the current location, and jump to the given
1870/// offset.
1871static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1872 BitstreamCursor &Stream) {
1873 // Save the current parsing location so we can jump back at the end
1874 // of the VST read.
1875 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1876 Stream.JumpToBit(Offset * 32);
1877#ifndef NDEBUG
1878 // Do some checking if we are in debug mode.
1879 BitstreamEntry Entry = Stream.advance();
1880 assert(Entry.Kind == BitstreamEntry::SubBlock);
1881 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1882#else
1883 // In NDEBUG mode ignore the output so we don't get an unused variable
1884 // warning.
1885 Stream.advance();
1886#endif
1887 return CurrentBit;
1888}
1889
Teresa Johnsonff642b92015-09-17 20:12:00 +00001890/// Parse the value symbol table at either the current parsing location or
1891/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001892std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001893 uint64_t CurrentBit;
1894 // Pass in the Offset to distinguish between calling for the module-level
1895 // VST (where we want to jump to the VST offset) and the function-level
1896 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001897 if (Offset > 0)
1898 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001899
1900 // Compute the delta between the bitcode indices in the VST (the word offset
1901 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1902 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1903 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1904 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1905 // just before entering the VST subblock because: 1) the EnterSubBlock
1906 // changes the AbbrevID width; 2) the VST block is nested within the same
1907 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1908 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1909 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1910 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1911 unsigned FuncBitcodeOffsetDelta =
1912 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1913
Chris Lattner982ec1e2007-05-05 00:17:00 +00001914 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001915 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001916
1917 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001918
David Majnemer3087b222015-01-20 05:58:07 +00001919 Triple TT(TheModule->getTargetTriple());
1920
Chris Lattnerccaa4482007-04-23 21:26:05 +00001921 // Read all the records for this value table.
1922 SmallString<128> ValueName;
1923 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001924 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001925
Chris Lattner27d38752013-01-20 02:13:19 +00001926 switch (Entry.Kind) {
1927 case BitstreamEntry::SubBlock: // Handled for us already.
1928 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001929 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001930 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001931 if (Offset > 0)
1932 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001933 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001934 case BitstreamEntry::Record:
1935 // The interesting case.
1936 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001938
Chris Lattnerccaa4482007-04-23 21:26:05 +00001939 // Read a record.
1940 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001941 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001942 default: // Default behavior: unknown type.
1943 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001944 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001945 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1946 if (std::error_code EC = ValOrErr.getError())
1947 return EC;
1948 ValOrErr.get();
1949 break;
1950 }
1951 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001952 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001953 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1954 if (std::error_code EC = ValOrErr.getError())
1955 return EC;
1956 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001957
Teresa Johnsonff642b92015-09-17 20:12:00 +00001958 auto *GO = dyn_cast<GlobalObject>(V);
1959 if (!GO) {
1960 // If this is an alias, need to get the actual Function object
1961 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1962 auto *GA = dyn_cast<GlobalAlias>(V);
1963 if (GA)
1964 GO = GA->getBaseObject();
1965 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001966 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001967
1968 uint64_t FuncWordOffset = Record[1];
1969 Function *F = dyn_cast<Function>(GO);
1970 assert(F);
1971 uint64_t FuncBitOffset = FuncWordOffset * 32;
1972 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001973 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001974 // Later when parsing is resumed after function materialization,
1975 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001976 if (FuncBitOffset > LastFunctionBlockBit)
1977 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001978 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001979 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001980 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001981 if (convertToString(Record, 1, ValueName))
1982 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001983 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001984 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001985 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Daniel Dunbard786b512009-07-26 00:34:27 +00001987 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001988 ValueName.clear();
1989 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001990 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001991 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001992 }
1993}
1994
Teresa Johnson12545072015-11-15 02:00:09 +00001995/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1996std::error_code
1997BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1998 if (Record.size() < 2)
1999 return error("Invalid record");
2000
2001 unsigned Kind = Record[0];
2002 SmallString<8> Name(Record.begin() + 1, Record.end());
2003
2004 unsigned NewKind = TheModule->getMDKindID(Name.str());
2005 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2006 return error("Conflicting METADATA_KIND records");
2007 return std::error_code();
2008}
2009
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002010static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2011
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002012std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
2013 StringRef Blob,
2014 unsigned &NextMetadataNo) {
2015 // All the MDStrings in the block are emitted together in a single
2016 // record. The strings are concatenated and stored in a blob along with
2017 // their sizes.
2018 if (Record.size() != 2)
2019 return error("Invalid record: metadata strings layout");
2020
2021 unsigned NumStrings = Record[0];
2022 unsigned StringsOffset = Record[1];
2023 if (!NumStrings)
2024 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00002025 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002026 return error("Invalid record: metadata strings corrupt offset");
2027
2028 StringRef Lengths = Blob.slice(0, StringsOffset);
2029 SimpleBitstreamCursor R(*StreamFile);
2030 R.jumpToPointer(Lengths.begin());
2031
2032 // Ensure that Blob doesn't get invalidated, even if this is reading from
2033 // a StreamingMemoryObject with corrupt data.
2034 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
2035
2036 StringRef Strings = Blob.drop_front(StringsOffset);
2037 do {
2038 if (R.AtEndOfStream())
2039 return error("Invalid record: metadata strings bad length");
2040
2041 unsigned Size = R.ReadVBR(6);
2042 if (Strings.size() < Size)
2043 return error("Invalid record: metadata strings truncated chars");
2044
2045 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
2046 NextMetadataNo++);
2047 Strings = Strings.drop_front(Size);
2048 } while (--NumStrings);
2049
2050 return std::error_code();
2051}
2052
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002053namespace {
2054class PlaceholderQueue {
2055 // Placeholders would thrash around when moved, so store in a std::deque
2056 // instead of some sort of vector.
2057 std::deque<DistinctMDOperandPlaceholder> PHs;
2058
2059public:
2060 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
2061 void flush(BitcodeReaderMetadataList &MetadataList);
2062};
2063} // end namespace
2064
2065DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
2066 PHs.emplace_back(ID);
2067 return PHs.back();
2068}
2069
2070void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
2071 while (!PHs.empty()) {
2072 PHs.front().replaceUseWith(
2073 MetadataList.getMetadataFwdRef(PHs.front().getID()));
2074 PHs.pop_front();
2075 }
2076}
2077
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00002078/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
2079/// module level metadata.
2080std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002081 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002082 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00002083
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00002084 if (!ModuleLevel && MetadataList.hasFwdRefs())
2085 return error("Invalid metadata: fwd refs into function blocks");
2086
Devang Patel7428d8a2009-07-22 17:43:22 +00002087 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002088 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002089
Adrian Prantl75819ae2016-04-15 15:57:41 +00002090 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
Devang Patel7428d8a2009-07-22 17:43:22 +00002091 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002092
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002093 PlaceholderQueue Placeholders;
2094 bool IsDistinct;
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002095 auto getMD = [&](unsigned ID) -> Metadata * {
2096 if (!IsDistinct)
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002097 return MetadataList.getMetadataFwdRef(ID);
2098 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
2099 return MD;
2100 return &Placeholders.getPlaceholderOp(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002101 };
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002102 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002103 if (ID)
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002104 return getMD(ID - 1);
2105 return nullptr;
2106 };
2107 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
2108 if (ID)
2109 return MetadataList.getMetadataFwdRef(ID - 1);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002110 return nullptr;
2111 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002112 auto getMDString = [&](unsigned ID) -> MDString *{
2113 // This requires that the ID is not really a forward reference. In
2114 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002115 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002116 };
2117
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002118 // Support for old type refs.
2119 auto getDITypeRefOrNull = [&](unsigned ID) {
2120 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
2121 };
2122
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002123#define GET_OR_DISTINCT(CLASS, ARGS) \
2124 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002125
Devang Patel7428d8a2009-07-22 17:43:22 +00002126 // Read all the records.
2127 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002128 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002129
Chris Lattner27d38752013-01-20 02:13:19 +00002130 switch (Entry.Kind) {
2131 case BitstreamEntry::SubBlock: // Handled for us already.
2132 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002133 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002134 case BitstreamEntry::EndBlock:
Adrian Prantl75819ae2016-04-15 15:57:41 +00002135 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
2136 for (auto CU_SP : CUSubprograms)
2137 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
2138 for (auto &Op : SPs->operands())
2139 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
2140 SP->replaceOperandWith(7, CU_SP.first);
2141
Teresa Johnson61b406e2015-12-29 23:00:22 +00002142 MetadataList.tryToResolveCycles();
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002143 Placeholders.flush(MetadataList);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002144 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002145 case BitstreamEntry::Record:
2146 // The interesting case.
2147 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002148 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002149
Devang Patel7428d8a2009-07-22 17:43:22 +00002150 // Read a record.
2151 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002152 StringRef Blob;
2153 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002154 IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00002155 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00002156 default: // Default behavior: ignore.
2157 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00002158 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00002159 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002160 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00002161 Record.clear();
2162 Code = Stream.ReadCode();
2163
Chris Lattner27d38752013-01-20 02:13:19 +00002164 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00002165 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002166 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00002167
2168 // Read named metadata elements.
2169 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00002170 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00002171 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00002172 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002173 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002174 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002175 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002176 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002177 break;
2178 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002179 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002180 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002181 // This is a LocalAsMetadata record, the only type of function-local
2182 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002183 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002184 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002185
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002186 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2187 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002188 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002189 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002190 };
2191 if (Record.size() != 2) {
2192 dropRecord();
2193 break;
2194 }
2195
2196 Type *Ty = getTypeByID(Record[0]);
2197 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2198 dropRecord();
2199 break;
2200 }
2201
Teresa Johnson61b406e2015-12-29 23:00:22 +00002202 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002203 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002204 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002205 break;
2206 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002207 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002208 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002209 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002210 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002211
Devang Patele059ba6e2009-07-23 01:07:34 +00002212 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002213 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002214 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002215 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002216 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002217 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002218 if (Ty->isMetadataTy())
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002219 Elts.push_back(getMD(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002220 else if (!Ty->isVoidTy()) {
2221 auto *MD =
2222 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2223 assert(isa<ConstantAsMetadata>(MD) &&
2224 "Expected non-function-local metadata");
2225 Elts.push_back(MD);
2226 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002227 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002228 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002229 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002230 break;
2231 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002232 case bitc::METADATA_VALUE: {
2233 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002234 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002235
2236 Type *Ty = getTypeByID(Record[0]);
2237 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002238 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002239
Teresa Johnson61b406e2015-12-29 23:00:22 +00002240 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002241 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002242 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002243 break;
2244 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002245 case bitc::METADATA_DISTINCT_NODE:
2246 IsDistinct = true;
2247 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002248 case bitc::METADATA_NODE: {
2249 SmallVector<Metadata *, 8> Elts;
2250 Elts.reserve(Record.size());
2251 for (unsigned ID : Record)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002252 Elts.push_back(getMDOrNull(ID));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002253 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2254 : MDNode::get(Context, Elts),
2255 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002256 break;
2257 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002258 case bitc::METADATA_LOCATION: {
2259 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002260 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002261
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002262 IsDistinct = Record[0];
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002263 unsigned Line = Record[1];
2264 unsigned Column = Record[2];
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002265 Metadata *Scope = getMD(Record[3]);
2266 Metadata *InlinedAt = getMDOrNull(Record[4]);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002267 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002268 GET_OR_DISTINCT(DILocation,
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002269 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002270 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002271 break;
2272 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002273 case bitc::METADATA_GENERIC_DEBUG: {
2274 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002275 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002276
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002277 IsDistinct = Record[0];
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002278 unsigned Tag = Record[1];
2279 unsigned Version = Record[2];
2280
2281 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002282 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002283
2284 auto *Header = getMDString(Record[3]);
2285 SmallVector<Metadata *, 8> DwarfOps;
2286 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002287 DwarfOps.push_back(getMDOrNull(Record[I]));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002288 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002289 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002290 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002291 break;
2292 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002293 case bitc::METADATA_SUBRANGE: {
2294 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002295 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002296
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002297 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002298 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002299 GET_OR_DISTINCT(DISubrange,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002300 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002301 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002302 break;
2303 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002304 case bitc::METADATA_ENUMERATOR: {
2305 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002306 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002307
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002308 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002309 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002310 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
2311 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002312 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002313 break;
2314 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002315 case bitc::METADATA_BASIC_TYPE: {
2316 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002317 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002318
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002319 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002320 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002321 GET_OR_DISTINCT(DIBasicType,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002322 (Context, Record[1], getMDString(Record[2]),
2323 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002324 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002325 break;
2326 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002327 case bitc::METADATA_DERIVED_TYPE: {
2328 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002329 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002330
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002331 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002332 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002333 GET_OR_DISTINCT(DIDerivedType,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002334 (Context, Record[1], getMDString(Record[2]),
2335 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002336 getDITypeRefOrNull(Record[5]),
2337 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2338 Record[9], Record[10], getMDOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002339 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002340 break;
2341 }
2342 case bitc::METADATA_COMPOSITE_TYPE: {
2343 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002344 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002345
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002346 // If we have a UUID and this is not a forward declaration, lookup the
2347 // mapping.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002348 IsDistinct = Record[0] & 0x1;
2349 bool IsNotUsedInTypeRef = Record[0] >= 2;
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002350 unsigned Tag = Record[1];
2351 MDString *Name = getMDString(Record[2]);
2352 Metadata *File = getMDOrNull(Record[3]);
2353 unsigned Line = Record[4];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002354 Metadata *Scope = getDITypeRefOrNull(Record[5]);
2355 Metadata *BaseType = getDITypeRefOrNull(Record[6]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002356 uint64_t SizeInBits = Record[7];
2357 uint64_t AlignInBits = Record[8];
2358 uint64_t OffsetInBits = Record[9];
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002359 unsigned Flags = Record[10];
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002360 Metadata *Elements = getMDOrNull(Record[11]);
2361 unsigned RuntimeLang = Record[12];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002362 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002363 Metadata *TemplateParams = getMDOrNull(Record[14]);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002364 auto *Identifier = getMDString(Record[15]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002365 DICompositeType *CT = nullptr;
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00002366 if (Identifier)
2367 CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002368 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2369 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2370 VTableHolder, TemplateParams);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002371
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002372 // Create a node if we didn't get a lazy ODR type.
2373 if (!CT)
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002374 CT = GET_OR_DISTINCT(DICompositeType,
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002375 (Context, Tag, Name, File, Line, Scope, BaseType,
2376 SizeInBits, AlignInBits, OffsetInBits, Flags,
2377 Elements, RuntimeLang, VTableHolder,
2378 TemplateParams, Identifier));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002379 if (!IsNotUsedInTypeRef && Identifier)
2380 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002381
2382 MetadataList.assignValue(CT, NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002383 break;
2384 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002385 case bitc::METADATA_SUBROUTINE_TYPE: {
2386 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002387 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002388
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002389 IsDistinct = Record[0] & 0x1;
2390 bool IsOldTypeRefArray = Record[0] < 2;
2391 Metadata *Types = getMDOrNull(Record[2]);
2392 if (LLVM_UNLIKELY(IsOldTypeRefArray))
2393 Types = MetadataList.upgradeTypeRefArray(Types);
2394
Teresa Johnson61b406e2015-12-29 23:00:22 +00002395 MetadataList.assignValue(
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002396 GET_OR_DISTINCT(DISubroutineType, (Context, Record[1], Types)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002397 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002398 break;
2399 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002400
2401 case bitc::METADATA_MODULE: {
2402 if (Record.size() != 6)
2403 return error("Invalid record");
2404
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002405 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002406 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002407 GET_OR_DISTINCT(DIModule,
Adrian Prantlab1243f2015-06-29 23:03:47 +00002408 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002409 getMDString(Record[2]), getMDString(Record[3]),
2410 getMDString(Record[4]), getMDString(Record[5]))),
2411 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002412 break;
2413 }
2414
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002415 case bitc::METADATA_FILE: {
2416 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002417 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002418
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002419 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002420 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002421 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2422 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002423 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002424 break;
2425 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002426 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002427 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002428 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002429
Amjad Abouda9bcf162015-12-10 12:56:35 +00002430 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002431 // distinct. It's always distinct.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002432 IsDistinct = true;
Adrian Prantl75819ae2016-04-15 15:57:41 +00002433 auto *CU = DICompileUnit::getDistinct(
2434 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2435 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2436 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2437 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2438 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2439 Record.size() <= 14 ? 0 : Record[14]);
2440
2441 MetadataList.assignValue(CU, NextMetadataNo++);
2442
2443 // Move the Upgrade the list of subprograms.
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002444 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
Adrian Prantl75819ae2016-04-15 15:57:41 +00002445 CUSubprograms.push_back({CU, SPs});
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002446 break;
2447 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002448 case bitc::METADATA_SUBPROGRAM: {
Peter Collingbourned4bff302015-11-05 22:03:56 +00002449 if (Record.size() != 18 && Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002450 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002451
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002452 IsDistinct =
2453 Record[0] || Record[8]; // All definitions should be distinct.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002454 // Version 1 has a Function as Record[15].
2455 // Version 2 has removed Record[15].
2456 // Version 3 has the Unit as Record[15].
2457 Metadata *CUorFn = getMDOrNull(Record[15]);
2458 unsigned Offset = Record.size() == 19 ? 1 : 0;
2459 bool HasFn = Offset && dyn_cast_or_null<ConstantAsMetadata>(CUorFn);
2460 bool HasCU = Offset && !HasFn;
Peter Collingbourned4bff302015-11-05 22:03:56 +00002461 DISubprogram *SP = GET_OR_DISTINCT(
2462 DISubprogram,
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002463 (Context, getDITypeRefOrNull(Record[1]), getMDString(Record[2]),
Peter Collingbourned4bff302015-11-05 22:03:56 +00002464 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2465 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002466 getDITypeRefOrNull(Record[10]), Record[11], Record[12], Record[13],
Adrian Prantl75819ae2016-04-15 15:57:41 +00002467 Record[14], HasCU ? CUorFn : nullptr,
2468 getMDOrNull(Record[15 + Offset]), getMDOrNull(Record[16 + Offset]),
2469 getMDOrNull(Record[17 + Offset])));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002470 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002471
2472 // Upgrade sp->function mapping to function->sp mapping.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002473 if (HasFn) {
2474 if (auto *CMD = dyn_cast<ConstantAsMetadata>(CUorFn))
Peter Collingbourned4bff302015-11-05 22:03:56 +00002475 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2476 if (F->isMaterializable())
2477 // Defer until materialized; unmaterialized functions may not have
2478 // metadata.
2479 FunctionsWithSPs[F] = SP;
2480 else if (!F->empty())
2481 F->setSubprogram(SP);
2482 }
2483 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002484 break;
2485 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002486 case bitc::METADATA_LEXICAL_BLOCK: {
2487 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002488 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002489
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002490 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002491 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002492 GET_OR_DISTINCT(DILexicalBlock,
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002493 (Context, getMDOrNull(Record[1]),
2494 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002495 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002496 break;
2497 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002498 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2499 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002500 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002501
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002502 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002503 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002504 GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002505 (Context, getMDOrNull(Record[1]),
2506 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002507 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002508 break;
2509 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002510 case bitc::METADATA_NAMESPACE: {
2511 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002512 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002513
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002514 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002515 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002516 GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
2517 getMDOrNull(Record[2]),
2518 getMDString(Record[3]), Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002519 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002520 break;
2521 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002522 case bitc::METADATA_MACRO: {
2523 if (Record.size() != 5)
2524 return error("Invalid record");
2525
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002526 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002527 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002528 GET_OR_DISTINCT(DIMacro,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002529 (Context, Record[1], Record[2],
2530 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002531 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002532 break;
2533 }
2534 case bitc::METADATA_MACRO_FILE: {
2535 if (Record.size() != 5)
2536 return error("Invalid record");
2537
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002538 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002539 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002540 GET_OR_DISTINCT(DIMacroFile,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002541 (Context, Record[1], Record[2],
2542 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002543 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002544 break;
2545 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002546 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002547 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002548 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002549
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002550 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002551 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Teresa Johnson61b406e2015-12-29 23:00:22 +00002552 (Context, getMDString(Record[1]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002553 getDITypeRefOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002554 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002555 break;
2556 }
2557 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002558 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002559 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002560
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002561 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002562 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002563 GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002564 (Context, Record[1], getMDString(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002565 getDITypeRefOrNull(Record[3]),
2566 getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002567 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002568 break;
2569 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002570 case bitc::METADATA_GLOBAL_VAR: {
2571 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002572 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002573
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002574 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002575 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002576 GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002577 (Context, getMDOrNull(Record[1]),
2578 getMDString(Record[2]), getMDString(Record[3]),
2579 getMDOrNull(Record[4]), Record[5],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002580 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002581 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002582 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002583 break;
2584 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002585 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002586 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002587 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002588 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002589
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002590 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2591 // DW_TAG_arg_variable.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002592 IsDistinct = Record[0];
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002593 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002594 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002595 GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002596 (Context, getMDOrNull(Record[1 + HasTag]),
2597 getMDString(Record[2 + HasTag]),
2598 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002599 getDITypeRefOrNull(Record[5 + HasTag]),
2600 Record[6 + HasTag], Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002601 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002602 break;
2603 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002604 case bitc::METADATA_EXPRESSION: {
2605 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002606 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002607
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002608 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002609 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002610 GET_OR_DISTINCT(DIExpression,
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002611 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002612 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002613 break;
2614 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002615 case bitc::METADATA_OBJC_PROPERTY: {
2616 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002617 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002618
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002619 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002620 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002621 GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002622 (Context, getMDString(Record[1]),
2623 getMDOrNull(Record[2]), Record[3],
2624 getMDString(Record[4]), getMDString(Record[5]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002625 Record[6], getDITypeRefOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002626 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002627 break;
2628 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002629 case bitc::METADATA_IMPORTED_ENTITY: {
2630 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002631 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002632
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002633 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002634 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002635 GET_OR_DISTINCT(DIImportedEntity,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002636 (Context, Record[1], getMDOrNull(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002637 getDITypeRefOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002638 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002639 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002640 break;
2641 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002642 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002643 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002644
2645 // Test for upgrading !llvm.loop.
2646 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2647
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002648 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002649 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002650 break;
2651 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002652 case bitc::METADATA_STRINGS:
2653 if (std::error_code EC =
2654 parseMetadataStrings(Record, Blob, NextMetadataNo))
2655 return EC;
2656 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002657 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002658 // Support older bitcode files that had METADATA_KIND records in a
2659 // block with METADATA_BLOCK_ID.
2660 if (std::error_code EC = parseMetadataKindRecord(Record))
2661 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002662 break;
2663 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002664 }
2665 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002666#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002667}
2668
Teresa Johnson12545072015-11-15 02:00:09 +00002669/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2670std::error_code BitcodeReader::parseMetadataKinds() {
2671 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2672 return error("Invalid record");
2673
2674 SmallVector<uint64_t, 64> Record;
2675
2676 // Read all the records.
2677 while (1) {
2678 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2679
2680 switch (Entry.Kind) {
2681 case BitstreamEntry::SubBlock: // Handled for us already.
2682 case BitstreamEntry::Error:
2683 return error("Malformed block");
2684 case BitstreamEntry::EndBlock:
2685 return std::error_code();
2686 case BitstreamEntry::Record:
2687 // The interesting case.
2688 break;
2689 }
2690
2691 // Read a record.
2692 Record.clear();
2693 unsigned Code = Stream.readRecord(Entry.ID, Record);
2694 switch (Code) {
2695 default: // Default behavior: ignore.
2696 break;
2697 case bitc::METADATA_KIND: {
2698 if (std::error_code EC = parseMetadataKindRecord(Record))
2699 return EC;
2700 break;
2701 }
2702 }
2703 }
2704}
2705
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002706/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2707/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002708uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002709 if ((V & 1) == 0)
2710 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002711 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002712 return -(V >> 1);
2713 // There is no such thing as -0 with integers. "-0" really means MININT.
2714 return 1ULL << 63;
2715}
2716
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002717/// Resolve all of the initializers for global values and aliases that we can.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002718std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002719 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002720 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2721 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002722 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002723 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002724 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002725
Chris Lattner44c17072007-04-26 02:46:40 +00002726 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002727 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002728 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002729 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002730 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002731
2732 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002733 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002734 if (ValID >= ValueList.size()) {
2735 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002736 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002737 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002738 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002739 GlobalInitWorklist.back().first->setInitializer(C);
2740 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002741 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002742 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002743 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002744 }
2745
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002746 while (!IndirectSymbolInitWorklist.empty()) {
2747 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002748 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002749 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002750 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002751 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2752 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002753 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002754 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2755 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002756 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002757 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002758 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002759 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002760 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002761
2762 while (!FunctionPrefixWorklist.empty()) {
2763 unsigned ValID = FunctionPrefixWorklist.back().second;
2764 if (ValID >= ValueList.size()) {
2765 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2766 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002767 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002768 FunctionPrefixWorklist.back().first->setPrefixData(C);
2769 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002770 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002771 }
2772 FunctionPrefixWorklist.pop_back();
2773 }
2774
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002775 while (!FunctionPrologueWorklist.empty()) {
2776 unsigned ValID = FunctionPrologueWorklist.back().second;
2777 if (ValID >= ValueList.size()) {
2778 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2779 } else {
2780 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2781 FunctionPrologueWorklist.back().first->setPrologueData(C);
2782 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002783 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002784 }
2785 FunctionPrologueWorklist.pop_back();
2786 }
2787
David Majnemer7fddecc2015-06-17 20:52:32 +00002788 while (!FunctionPersonalityFnWorklist.empty()) {
2789 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2790 if (ValID >= ValueList.size()) {
2791 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2792 } else {
2793 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2794 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2795 else
2796 return error("Expected a constant");
2797 }
2798 FunctionPersonalityFnWorklist.pop_back();
2799 }
2800
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002801 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002802}
2803
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002804static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002805 SmallVector<uint64_t, 8> Words(Vals.size());
2806 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002807 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002808
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002809 return APInt(TypeBits, Words);
2810}
2811
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002812std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002813 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002814 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002815
2816 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002817
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002818 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002819 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002820 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002821 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002822 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002823
Chris Lattner27d38752013-01-20 02:13:19 +00002824 switch (Entry.Kind) {
2825 case BitstreamEntry::SubBlock: // Handled for us already.
2826 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002827 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002828 case BitstreamEntry::EndBlock:
2829 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002830 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002831
Chris Lattner27d38752013-01-20 02:13:19 +00002832 // Once all the constants have been read, go through and resolve forward
2833 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002834 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002835 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002836 case BitstreamEntry::Record:
2837 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002838 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002839 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002841 // Read a record.
2842 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002843 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002844 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002845 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002846 default: // Default behavior: unknown constant
2847 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002848 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002849 break;
2850 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2851 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002852 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002853 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002854 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002855 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002856 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002857 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002858 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002859 break;
2860 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002861 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002862 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002863 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002864 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002865 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002866 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002867 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002869 APInt VInt =
2870 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002871 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002872
Chris Lattner08feb1e2007-04-24 04:04:35 +00002873 break;
2874 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002875 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002876 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002877 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002878 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002879 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2880 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002881 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002882 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2883 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002884 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002885 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2886 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002887 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002888 // Bits are not stored the same way as a normal i80 APInt, compensate.
2889 uint64_t Rearrange[2];
2890 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2891 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002892 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2893 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002894 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002895 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2896 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002897 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002898 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2899 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002900 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002901 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002902 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002903 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002904
Chris Lattnere14cb882007-05-04 19:11:41 +00002905 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2906 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002907 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002908
Chris Lattnere14cb882007-05-04 19:11:41 +00002909 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002910 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002911
Chris Lattner229907c2011-07-18 04:54:35 +00002912 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002913 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002914 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002915 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002916 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002917 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2918 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002919 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002920 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002921 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002922 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2923 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002924 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002925 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002926 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002927 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002928 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002929 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002930 break;
2931 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002932 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002933 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2934 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002935 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002936
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002937 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002938 V = ConstantDataArray::getString(Context, Elts,
2939 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002940 break;
2941 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002942 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2943 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002944 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002945
Chris Lattner372dd1e2012-01-30 00:51:16 +00002946 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002947 if (EltTy->isIntegerTy(8)) {
2948 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2949 if (isa<VectorType>(CurTy))
2950 V = ConstantDataVector::get(Context, Elts);
2951 else
2952 V = ConstantDataArray::get(Context, Elts);
2953 } else if (EltTy->isIntegerTy(16)) {
2954 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2955 if (isa<VectorType>(CurTy))
2956 V = ConstantDataVector::get(Context, Elts);
2957 else
2958 V = ConstantDataArray::get(Context, Elts);
2959 } else if (EltTy->isIntegerTy(32)) {
2960 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2961 if (isa<VectorType>(CurTy))
2962 V = ConstantDataVector::get(Context, Elts);
2963 else
2964 V = ConstantDataArray::get(Context, Elts);
2965 } else if (EltTy->isIntegerTy(64)) {
2966 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2967 if (isa<VectorType>(CurTy))
2968 V = ConstantDataVector::get(Context, Elts);
2969 else
2970 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002971 } else if (EltTy->isHalfTy()) {
2972 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2973 if (isa<VectorType>(CurTy))
2974 V = ConstantDataVector::getFP(Context, Elts);
2975 else
2976 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002977 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002978 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002979 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002980 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002981 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002982 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002983 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002984 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002985 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002986 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002987 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002988 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002989 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002990 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002991 }
2992 break;
2993 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002994 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002995 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002996 return error("Invalid record");
2997 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002998 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002999 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00003000 } else {
3001 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3002 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00003003 unsigned Flags = 0;
3004 if (Record.size() >= 4) {
3005 if (Opc == Instruction::Add ||
3006 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003007 Opc == Instruction::Mul ||
3008 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00003009 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3010 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3011 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3012 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003013 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003014 Opc == Instruction::UDiv ||
3015 Opc == Instruction::LShr ||
3016 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003017 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003018 Flags |= SDivOperator::IsExact;
3019 }
3020 }
3021 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00003022 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003023 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003024 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003025 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003026 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003027 return error("Invalid record");
3028 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00003029 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003030 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00003031 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00003032 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003033 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003034 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00003035 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003036 V = UpgradeBitCastExpr(Opc, Op, CurTy);
3037 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003038 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003039 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003040 }
Dan Gohman1639c392009-07-27 21:53:46 +00003041 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003042 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00003043 unsigned OpNum = 0;
3044 Type *PointeeType = nullptr;
3045 if (Record.size() % 2)
3046 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003047 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00003048 while (OpNum != Record.size()) {
3049 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003050 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003051 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00003052 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003053 }
David Blaikieb9263572015-03-13 21:03:36 +00003054
David Blaikieb9263572015-03-13 21:03:36 +00003055 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00003056 PointeeType !=
3057 cast<SequentialType>(Elts[0]->getType()->getScalarType())
3058 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003059 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00003060 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003061
3062 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3063 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3064 BitCode ==
3065 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00003066 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003067 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00003068 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003069 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003070 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00003071
3072 Type *SelectorTy = Type::getInt1Ty(Context);
3073
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003074 // The selector might be an i1 or an <n x i1>
3075 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00003076 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003077 if (Value *V = ValueList[Record[0]])
3078 if (SelectorTy != V->getType())
3079 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00003080
3081 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3082 SelectorTy),
3083 ValueList.getConstantFwdRef(Record[1],CurTy),
3084 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003085 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00003086 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003087 case bitc::CST_CODE_CE_EXTRACTELT
3088 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003089 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003090 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003091 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003092 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003093 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003094 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003095 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003096 Constant *Op1 = nullptr;
3097 if (Record.size() == 4) {
3098 Type *IdxTy = getTypeByID(Record[2]);
3099 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003100 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003101 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3102 } else // TODO: Remove with llvm 4.0
3103 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3104 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003105 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003106 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003107 break;
3108 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003109 case bitc::CST_CODE_CE_INSERTELT
3110 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003111 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003112 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003113 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003114 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3115 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3116 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003117 Constant *Op2 = nullptr;
3118 if (Record.size() == 4) {
3119 Type *IdxTy = getTypeByID(Record[2]);
3120 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003121 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003122 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3123 } else // TODO: Remove with llvm 4.0
3124 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3125 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003126 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003127 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003128 break;
3129 }
3130 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003131 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003132 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003133 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003134 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3135 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003136 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003137 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003138 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003139 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003140 break;
3141 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00003142 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003143 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3144 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00003145 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003146 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003147 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00003148 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3149 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003150 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003151 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00003152 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003153 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00003154 break;
3155 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003156 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003157 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003158 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003159 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003160 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003161 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003162 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3163 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3164
Duncan Sands9dff9be2010-02-15 16:12:20 +00003165 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00003166 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00003167 else
Owen Anderson487375e2009-07-29 18:55:55 +00003168 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003169 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00003170 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003171 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00003172 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003173 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003174 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003175 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003176 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00003177 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003178 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003179 unsigned AsmStrSize = Record[1];
3180 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003181 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003182 unsigned ConstStrSize = Record[2+AsmStrSize];
3183 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003184 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003185
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003186 for (unsigned i = 0; i != AsmStrSize; ++i)
3187 AsmStr += (char)Record[2+i];
3188 for (unsigned i = 0; i != ConstStrSize; ++i)
3189 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00003190 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003191 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003192 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003193 break;
3194 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003195 // This version adds support for the asm dialect keywords (e.g.,
3196 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003197 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003198 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003199 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003200 std::string AsmStr, ConstrStr;
3201 bool HasSideEffects = Record[0] & 1;
3202 bool IsAlignStack = (Record[0] >> 1) & 1;
3203 unsigned AsmDialect = Record[0] >> 2;
3204 unsigned AsmStrSize = Record[1];
3205 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003206 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003207 unsigned ConstStrSize = Record[2+AsmStrSize];
3208 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003209 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003210
3211 for (unsigned i = 0; i != AsmStrSize; ++i)
3212 AsmStr += (char)Record[2+i];
3213 for (unsigned i = 0; i != ConstStrSize; ++i)
3214 ConstrStr += (char)Record[3+AsmStrSize+i];
3215 PointerType *PTy = cast<PointerType>(CurTy);
3216 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3217 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00003218 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003219 break;
3220 }
Chris Lattner5956dc82009-10-28 05:53:48 +00003221 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00003222 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003223 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003224 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003225 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003226 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00003227 Function *Fn =
3228 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00003229 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003230 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003231
3232 // If the function is already parsed we can insert the block address right
3233 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003234 BasicBlock *BB;
3235 unsigned BBID = Record[2];
3236 if (!BBID)
3237 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003238 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003239 if (!Fn->empty()) {
3240 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003241 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003242 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003243 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003244 ++BBI;
3245 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003246 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003247 } else {
3248 // Otherwise insert a placeholder and remember it so it can be inserted
3249 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003250 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3251 if (FwdBBs.empty())
3252 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003253 if (FwdBBs.size() < BBID + 1)
3254 FwdBBs.resize(BBID + 1);
3255 if (!FwdBBs[BBID])
3256 FwdBBs[BBID] = BasicBlock::Create(Context);
3257 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003258 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003259 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003260 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003261 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003262 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003263
David Majnemer8a1c45d2015-12-12 05:38:55 +00003264 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003265 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003266 }
3267}
Chris Lattner1314b992007-04-22 06:23:29 +00003268
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003269std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003270 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003271 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003272
Chad Rosierca2567b2011-12-07 21:44:12 +00003273 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003274 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003275 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003276 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003277
Chris Lattner27d38752013-01-20 02:13:19 +00003278 switch (Entry.Kind) {
3279 case BitstreamEntry::SubBlock: // Handled for us already.
3280 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003281 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003282 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003283 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003284 case BitstreamEntry::Record:
3285 // The interesting case.
3286 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003287 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003288
Chad Rosierca2567b2011-12-07 21:44:12 +00003289 // Read a use list record.
3290 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003291 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003292 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003293 default: // Default behavior: unknown type.
3294 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003295 case bitc::USELIST_CODE_BB:
3296 IsBB = true;
3297 // fallthrough
3298 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003299 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003300 if (RecordLength < 3)
3301 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003302 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003303 unsigned ID = Record.back();
3304 Record.pop_back();
3305
3306 Value *V;
3307 if (IsBB) {
3308 assert(ID < FunctionBBs.size() && "Basic block not found");
3309 V = FunctionBBs[ID];
3310 } else
3311 V = ValueList[ID];
3312 unsigned NumUses = 0;
3313 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003314 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003315 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003316 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003317 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003318 }
3319 if (Order.size() != Record.size() || NumUses > Record.size())
3320 // Mismatches can happen if the functions are being materialized lazily
3321 // (out-of-order), or a value has been upgraded.
3322 break;
3323
3324 V->sortUseList([&](const Use &L, const Use &R) {
3325 return Order.lookup(&L) < Order.lookup(&R);
3326 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003327 break;
3328 }
3329 }
3330 }
3331}
3332
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003333/// When we see the block for metadata, remember where it is and then skip it.
3334/// This lets us lazily deserialize the metadata.
3335std::error_code BitcodeReader::rememberAndSkipMetadata() {
3336 // Save the current stream state.
3337 uint64_t CurBit = Stream.GetCurrentBitNo();
3338 DeferredMetadataInfo.push_back(CurBit);
3339
3340 // Skip over the block for now.
3341 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003342 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003343 return std::error_code();
3344}
3345
3346std::error_code BitcodeReader::materializeMetadata() {
3347 for (uint64_t BitPos : DeferredMetadataInfo) {
3348 // Move the bit stream to the saved position.
3349 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003350 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003351 return EC;
3352 }
3353 DeferredMetadataInfo.clear();
3354 return std::error_code();
3355}
3356
Rafael Espindola468b8682015-04-01 14:44:59 +00003357void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003358
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003359/// When we see the block for a function body, remember where it is and then
3360/// skip it. This lets us lazily deserialize the functions.
3361std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003362 // Get the function we are talking about.
3363 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003364 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003365
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003366 Function *Fn = FunctionsWithBodies.back();
3367 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003368
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003369 // Save the current stream state.
3370 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003371 assert(
3372 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3373 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003374 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003375
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003376 // Skip over the function block for now.
3377 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003378 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003379 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003380}
3381
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003382std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003383 // Patch the initializers for globals and aliases up.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003384 resolveGlobalAndIndirectSymbolInits();
3385 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003386 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003387
3388 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003389 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003390 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003391 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003392 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003393 }
3394
3395 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003396 for (GlobalVariable &GV : TheModule->globals())
3397 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003398
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003399 // Force deallocation of memory for these vectors to favor the client that
3400 // want lazy deserialization.
3401 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003402 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3403 IndirectSymbolInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003404 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003405}
3406
Teresa Johnson1493ad92015-10-10 14:18:36 +00003407/// Support for lazy parsing of function bodies. This is required if we
3408/// either have an old bitcode file without a VST forward declaration record,
3409/// or if we have an anonymous function being materialized, since anonymous
3410/// functions do not have a name and are therefore not in the VST.
3411std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3412 Stream.JumpToBit(NextUnreadBit);
3413
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003414 if (Stream.AtEndOfStream())
3415 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003416
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003417 if (!SeenFirstFunctionBody)
3418 return error("Trying to materialize functions before seeing function blocks");
3419
Teresa Johnson1493ad92015-10-10 14:18:36 +00003420 // An old bitcode file with the symbol table at the end would have
3421 // finished the parse greedily.
3422 assert(SeenValueSymbolTable);
3423
3424 SmallVector<uint64_t, 64> Record;
3425
3426 while (1) {
3427 BitstreamEntry Entry = Stream.advance();
3428 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003429 default:
3430 return error("Expect SubBlock");
3431 case BitstreamEntry::SubBlock:
3432 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003433 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003434 return error("Expect function block");
3435 case bitc::FUNCTION_BLOCK_ID:
3436 if (std::error_code EC = rememberAndSkipFunctionBody())
3437 return EC;
3438 NextUnreadBit = Stream.GetCurrentBitNo();
3439 return std::error_code();
3440 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003441 }
3442 }
3443}
3444
Mehdi Amini5d303282015-10-26 18:37:00 +00003445std::error_code BitcodeReader::parseBitcodeVersion() {
3446 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3447 return error("Invalid record");
3448
3449 // Read all the records.
3450 SmallVector<uint64_t, 64> Record;
3451 while (1) {
3452 BitstreamEntry Entry = Stream.advance();
3453
3454 switch (Entry.Kind) {
3455 default:
3456 case BitstreamEntry::Error:
3457 return error("Malformed block");
3458 case BitstreamEntry::EndBlock:
3459 return std::error_code();
3460 case BitstreamEntry::Record:
3461 // The interesting case.
3462 break;
3463 }
3464
3465 // Read a record.
3466 Record.clear();
3467 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3468 switch (BitCode) {
3469 default: // Default behavior: reject
3470 return error("Invalid value");
3471 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3472 // N]
3473 convertToString(Record, 0, ProducerIdentification);
3474 break;
3475 }
3476 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3477 unsigned epoch = (unsigned)Record[0];
3478 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003479 return error(
3480 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3481 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003482 }
3483 }
3484 }
3485 }
3486}
3487
Teresa Johnson1493ad92015-10-10 14:18:36 +00003488std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003489 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003490 if (ResumeBit)
3491 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003492 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003493 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003494
Chris Lattner1314b992007-04-22 06:23:29 +00003495 SmallVector<uint64_t, 64> Record;
3496 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003497 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003498
3499 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003500 while (1) {
3501 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003502
Chris Lattner27d38752013-01-20 02:13:19 +00003503 switch (Entry.Kind) {
3504 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003505 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003506 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003507 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003508
Chris Lattner27d38752013-01-20 02:13:19 +00003509 case BitstreamEntry::SubBlock:
3510 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003511 default: // Skip unknown content.
3512 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003513 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003514 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003515 case bitc::BLOCKINFO_BLOCK_ID:
3516 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003517 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003518 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003519 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003520 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003521 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003522 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003523 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003524 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003525 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003526 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003527 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003528 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003529 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003530 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003531 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003532 if (!SeenValueSymbolTable) {
3533 // Either this is an old form VST without function index and an
3534 // associated VST forward declaration record (which would have caused
3535 // the VST to be jumped to and parsed before it was encountered
3536 // normally in the stream), or there were no function blocks to
3537 // trigger an earlier parsing of the VST.
3538 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3539 if (std::error_code EC = parseValueSymbolTable())
3540 return EC;
3541 SeenValueSymbolTable = true;
3542 } else {
3543 // We must have had a VST forward declaration record, which caused
3544 // the parser to jump to and parse the VST earlier.
3545 assert(VSTOffset > 0);
3546 if (Stream.SkipBlock())
3547 return error("Invalid record");
3548 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003549 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003550 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003551 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003552 return EC;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003553 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003554 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003555 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003556 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003557 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3558 if (std::error_code EC = rememberAndSkipMetadata())
3559 return EC;
3560 break;
3561 }
3562 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003563 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003564 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003565 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003566 case bitc::METADATA_KIND_BLOCK_ID:
3567 if (std::error_code EC = parseMetadataKinds())
3568 return EC;
3569 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003570 case bitc::FUNCTION_BLOCK_ID:
3571 // If this is the first function body we've seen, reverse the
3572 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003573 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003574 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003575 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003576 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003577 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003578 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003579
Teresa Johnsonff642b92015-09-17 20:12:00 +00003580 if (VSTOffset > 0) {
3581 // If we have a VST forward declaration record, make sure we
3582 // parse the VST now if we haven't already. It is needed to
3583 // set up the DeferredFunctionInfo vector for lazy reading.
3584 if (!SeenValueSymbolTable) {
3585 if (std::error_code EC =
3586 BitcodeReader::parseValueSymbolTable(VSTOffset))
3587 return EC;
3588 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003589 // Fall through so that we record the NextUnreadBit below.
3590 // This is necessary in case we have an anonymous function that
3591 // is later materialized. Since it will not have a VST entry we
3592 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003593 } else {
3594 // If we have a VST forward declaration record, but have already
3595 // parsed the VST (just above, when the first function body was
3596 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003597 // materializing functions. The ResumeBit points to the
3598 // start of the last function block recorded in the
3599 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003600 if (Stream.SkipBlock())
3601 return error("Invalid record");
3602 continue;
3603 }
3604 }
3605
3606 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003607 // index in the VST, nor a VST forward declaration record, as
3608 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003609 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003610 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003611 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003612
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003613 // Suspend parsing when we reach the function bodies. Subsequent
3614 // materialization calls will resume it when necessary. If the bitcode
3615 // file is old, the symbol table will be at the end instead and will not
3616 // have been seen yet. In this case, just finish the parse now.
3617 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003618 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003619 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003620 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003621 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003622 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003623 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003624 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003625 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003626 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3627 if (std::error_code EC = parseOperandBundleTags())
3628 return EC;
3629 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003630 }
3631 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003632
Chris Lattner27d38752013-01-20 02:13:19 +00003633 case BitstreamEntry::Record:
3634 // The interesting case.
3635 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003636 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003637
Chris Lattner1314b992007-04-22 06:23:29 +00003638 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003639 auto BitCode = Stream.readRecord(Entry.ID, Record);
3640 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003641 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003642 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003643 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003644 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003645 // Only version #0 and #1 are supported so far.
3646 unsigned module_version = Record[0];
3647 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003648 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003649 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003650 case 0:
3651 UseRelativeIDs = false;
3652 break;
3653 case 1:
3654 UseRelativeIDs = true;
3655 break;
3656 }
Chris Lattner1314b992007-04-22 06:23:29 +00003657 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003658 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003659 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003660 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003661 if (convertToString(Record, 0, S))
3662 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003663 TheModule->setTargetTriple(S);
3664 break;
3665 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003666 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003667 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003668 if (convertToString(Record, 0, S))
3669 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003670 TheModule->setDataLayout(S);
3671 break;
3672 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003673 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003674 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003675 if (convertToString(Record, 0, S))
3676 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003677 TheModule->setModuleInlineAsm(S);
3678 break;
3679 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003680 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3681 // FIXME: Remove in 4.0.
3682 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003683 if (convertToString(Record, 0, S))
3684 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003685 // Ignore value.
3686 break;
3687 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003688 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003689 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003690 if (convertToString(Record, 0, S))
3691 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003692 SectionTable.push_back(S);
3693 break;
3694 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003695 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003696 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003697 if (convertToString(Record, 0, S))
3698 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003699 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003700 break;
3701 }
David Majnemerdad0a642014-06-27 18:19:56 +00003702 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3703 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003704 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003705 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3706 unsigned ComdatNameSize = Record[1];
3707 std::string ComdatName;
3708 ComdatName.reserve(ComdatNameSize);
3709 for (unsigned i = 0; i != ComdatNameSize; ++i)
3710 ComdatName += (char)Record[2 + i];
3711 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3712 C->setSelectionKind(SK);
3713 ComdatList.push_back(C);
3714 break;
3715 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003716 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003717 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003718 // unnamed_addr, externally_initialized, dllstorageclass,
3719 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003720 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003721 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003722 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003723 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003724 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003725 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003726 bool isConstant = Record[1] & 1;
3727 bool explicitType = Record[1] & 2;
3728 unsigned AddressSpace;
3729 if (explicitType) {
3730 AddressSpace = Record[1] >> 2;
3731 } else {
3732 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003733 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003734 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3735 Ty = cast<PointerType>(Ty)->getElementType();
3736 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003737
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003738 uint64_t RawLinkage = Record[3];
3739 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003740 unsigned Alignment;
3741 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3742 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003743 std::string Section;
3744 if (Record[5]) {
3745 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003746 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003747 Section = SectionTable[Record[5]-1];
3748 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003749 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003750 // Local linkage must have default visibility.
3751 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3752 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003753 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003754
3755 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003756 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003757 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003758
Rafael Espindola45e6c192011-01-08 16:42:36 +00003759 bool UnnamedAddr = false;
3760 if (Record.size() > 8)
3761 UnnamedAddr = Record[8];
3762
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003763 bool ExternallyInitialized = false;
3764 if (Record.size() > 9)
3765 ExternallyInitialized = Record[9];
3766
Chris Lattner1314b992007-04-22 06:23:29 +00003767 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003768 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003769 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003770 NewGV->setAlignment(Alignment);
3771 if (!Section.empty())
3772 NewGV->setSection(Section);
3773 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003774 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003775
Nico Rieck7157bb72014-01-14 15:22:47 +00003776 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003777 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003778 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003779 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003780
Chris Lattnerccaa4482007-04-23 21:26:05 +00003781 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003782
Chris Lattner47d131b2007-04-24 00:18:21 +00003783 // Remember which value to use for the global initializer.
3784 if (unsigned InitID = Record[2])
3785 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003786
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003787 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003788 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003789 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003790 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003791 NewGV->setComdat(ComdatList[ComdatID - 1]);
3792 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003793 } else if (hasImplicitComdat(RawLinkage)) {
3794 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3795 }
Chris Lattner1314b992007-04-22 06:23:29 +00003796 break;
3797 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003798 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003799 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003800 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003801 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003802 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003803 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003804 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003805 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003806 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003807 if (auto *PTy = dyn_cast<PointerType>(Ty))
3808 Ty = PTy->getElementType();
3809 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003810 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003811 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003812 auto CC = static_cast<CallingConv::ID>(Record[1]);
3813 if (CC & ~CallingConv::MaxID)
3814 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003815
Gabor Greife9ecc682008-04-06 20:25:17 +00003816 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3817 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003818
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003819 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003820 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003821 uint64_t RawLinkage = Record[3];
3822 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003823 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003824
JF Bastien30bf96b2015-02-22 19:32:03 +00003825 unsigned Alignment;
3826 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3827 return EC;
3828 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003829 if (Record[6]) {
3830 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003831 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003832 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003833 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003834 // Local linkage must have default visibility.
3835 if (!Func->hasLocalLinkage())
3836 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003837 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003838 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003839 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003840 return error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00003841 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00003842 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00003843 bool UnnamedAddr = false;
3844 if (Record.size() > 9)
3845 UnnamedAddr = Record[9];
3846 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003847 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003848 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003849
3850 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003851 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003852 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003853 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003854
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003855 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003856 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003857 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003858 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003859 Func->setComdat(ComdatList[ComdatID - 1]);
3860 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003861 } else if (hasImplicitComdat(RawLinkage)) {
3862 Func->setComdat(reinterpret_cast<Comdat *>(1));
3863 }
David Majnemerdad0a642014-06-27 18:19:56 +00003864
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003865 if (Record.size() > 13 && Record[13] != 0)
3866 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3867
David Majnemer7fddecc2015-06-17 20:52:32 +00003868 if (Record.size() > 14 && Record[14] != 0)
3869 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3870
Chris Lattnerccaa4482007-04-23 21:26:05 +00003871 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003872
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003873 // If this is a function with a body, remember the prototype we are
3874 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003875 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003876 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003877 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003878 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003879 }
Chris Lattner1314b992007-04-22 06:23:29 +00003880 break;
3881 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003882 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3883 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003884 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3885 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003886 case bitc::MODULE_CODE_ALIAS:
3887 case bitc::MODULE_CODE_ALIAS_OLD: {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003888 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003889 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003890 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003891 unsigned OpNum = 0;
3892 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003893 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003894 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003895
David Blaikie6a51dbd2015-09-17 22:18:59 +00003896 unsigned AddrSpace;
3897 if (!NewRecord) {
3898 auto *PTy = dyn_cast<PointerType>(Ty);
3899 if (!PTy)
3900 return error("Invalid type for value");
3901 Ty = PTy->getElementType();
3902 AddrSpace = PTy->getAddressSpace();
3903 } else {
3904 AddrSpace = Record[OpNum++];
3905 }
3906
3907 auto Val = Record[OpNum++];
3908 auto Linkage = Record[OpNum++];
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003909 GlobalIndirectSymbol *NewGA;
3910 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3911 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003912 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3913 "", TheModule);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003914 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003915 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3916 "", nullptr, TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003917 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003918 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003919 if (OpNum != Record.size()) {
3920 auto VisInd = OpNum++;
3921 if (!NewGA->hasLocalLinkage())
3922 // FIXME: Change to an error if non-default in 4.0.
3923 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3924 }
3925 if (OpNum != Record.size())
3926 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003927 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003928 upgradeDLLImportExportLinkage(NewGA, Linkage);
3929 if (OpNum != Record.size())
3930 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3931 if (OpNum != Record.size())
3932 NewGA->setUnnamedAddr(Record[OpNum++]);
Chris Lattner44c17072007-04-26 02:46:40 +00003933 ValueList.push_back(NewGA);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003934 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003935 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003936 }
Chris Lattner831d4202007-04-26 03:27:58 +00003937 /// MODULE_CODE_PURGEVALS: [numvals]
3938 case bitc::MODULE_CODE_PURGEVALS:
3939 // Trim down the value list to the specified size.
3940 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003941 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003942 ValueList.shrinkTo(Record[0]);
3943 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003944 /// MODULE_CODE_VSTOFFSET: [offset]
3945 case bitc::MODULE_CODE_VSTOFFSET:
3946 if (Record.size() < 1)
3947 return error("Invalid record");
3948 VSTOffset = Record[0];
3949 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003950 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3951 case bitc::MODULE_CODE_SOURCE_FILENAME:
3952 SmallString<128> ValueName;
3953 if (convertToString(Record, 0, ValueName))
3954 return error("Invalid record");
3955 TheModule->setSourceFileName(ValueName);
3956 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003957 }
Chris Lattner1314b992007-04-22 06:23:29 +00003958 Record.clear();
3959 }
Chris Lattner1314b992007-04-22 06:23:29 +00003960}
3961
Teresa Johnson403a7872015-10-04 14:33:43 +00003962/// Helper to read the header common to all bitcode files.
3963static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3964 // Sniff for the signature.
3965 if (Stream.Read(8) != 'B' ||
3966 Stream.Read(8) != 'C' ||
3967 Stream.Read(4) != 0x0 ||
3968 Stream.Read(4) != 0xC ||
3969 Stream.Read(4) != 0xE ||
3970 Stream.Read(4) != 0xD)
3971 return false;
3972 return true;
3973}
3974
Rafael Espindola1aabf982015-06-16 23:29:49 +00003975std::error_code
3976BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3977 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003978 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003979
Rafael Espindola1aabf982015-06-16 23:29:49 +00003980 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003981 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003982
Chris Lattner1314b992007-04-22 06:23:29 +00003983 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003984 if (!hasValidBitcodeHeader(Stream))
3985 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003986
Chris Lattner1314b992007-04-22 06:23:29 +00003987 // We expect a number of well-defined blocks, though we don't necessarily
3988 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003989 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003990 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003991 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003992 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003993 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003994
Chris Lattner27d38752013-01-20 02:13:19 +00003995 BitstreamEntry Entry =
3996 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003997
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003998 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003999 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00004000
Mehdi Amini5d303282015-10-26 18:37:00 +00004001 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4002 parseBitcodeVersion();
4003 continue;
4004 }
4005
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004006 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00004007 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00004008
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004009 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004010 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00004011 }
Chris Lattner1314b992007-04-22 06:23:29 +00004012}
Chris Lattner6694f602007-04-29 07:54:31 +00004013
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004014ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00004015 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004016 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00004017
4018 SmallVector<uint64_t, 64> Record;
4019
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004020 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00004021 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00004022 while (1) {
4023 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004024
Chris Lattner27d38752013-01-20 02:13:19 +00004025 switch (Entry.Kind) {
4026 case BitstreamEntry::SubBlock: // Handled for us already.
4027 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004028 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004029 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00004030 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00004031 case BitstreamEntry::Record:
4032 // The interesting case.
4033 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00004034 }
4035
4036 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00004037 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00004038 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00004039 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004040 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004041 if (convertToString(Record, 0, S))
4042 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004043 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00004044 break;
4045 }
4046 }
4047 Record.clear();
4048 }
Rafael Espindolae6107792014-07-04 20:05:56 +00004049 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00004050}
4051
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004052ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00004053 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004054 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00004055
4056 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004057 if (!hasValidBitcodeHeader(Stream))
4058 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00004059
4060 // We expect a number of well-defined blocks, though we don't necessarily
4061 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00004062 while (1) {
4063 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004064
Chris Lattner27d38752013-01-20 02:13:19 +00004065 switch (Entry.Kind) {
4066 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004067 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004068 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004069 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00004070
Chris Lattner27d38752013-01-20 02:13:19 +00004071 case BitstreamEntry::SubBlock:
4072 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00004073 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00004074
Chris Lattner27d38752013-01-20 02:13:19 +00004075 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00004076 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004077 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004078 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004079
Chris Lattner27d38752013-01-20 02:13:19 +00004080 case BitstreamEntry::Record:
4081 Stream.skipRecord(Entry.ID);
4082 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00004083 }
4084 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004085}
4086
Mehdi Amini3383ccc2015-11-09 02:46:41 +00004087ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
4088 if (std::error_code EC = initStream(nullptr))
4089 return EC;
4090
4091 // Sniff for the signature.
4092 if (!hasValidBitcodeHeader(Stream))
4093 return error("Invalid bitcode signature");
4094
4095 // We expect a number of well-defined blocks, though we don't necessarily
4096 // need to understand them all.
4097 while (1) {
4098 BitstreamEntry Entry = Stream.advance();
4099 switch (Entry.Kind) {
4100 case BitstreamEntry::Error:
4101 return error("Malformed block");
4102 case BitstreamEntry::EndBlock:
4103 return std::error_code();
4104
4105 case BitstreamEntry::SubBlock:
4106 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4107 if (std::error_code EC = parseBitcodeVersion())
4108 return EC;
4109 return ProducerIdentification;
4110 }
4111 // Ignore other sub-blocks.
4112 if (Stream.SkipBlock())
4113 return error("Malformed block");
4114 continue;
4115 case BitstreamEntry::Record:
4116 Stream.skipRecord(Entry.ID);
4117 continue;
4118 }
4119 }
4120}
4121
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004122/// Parse metadata attachments.
4123std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00004124 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004125 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004126
Devang Patelaf206b82009-09-18 19:26:43 +00004127 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00004128 while (1) {
4129 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004130
Chris Lattner27d38752013-01-20 02:13:19 +00004131 switch (Entry.Kind) {
4132 case BitstreamEntry::SubBlock: // Handled for us already.
4133 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004134 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004135 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004136 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00004137 case BitstreamEntry::Record:
4138 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00004139 break;
4140 }
Chris Lattner27d38752013-01-20 02:13:19 +00004141
Devang Patelaf206b82009-09-18 19:26:43 +00004142 // Read a metadata attachment record.
4143 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00004144 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00004145 default: // Default behavior: ignore.
4146 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00004147 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00004148 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004149 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004150 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004151 if (RecordLength % 2 == 0) {
4152 // A function attachment.
4153 for (unsigned I = 0; I != RecordLength; I += 2) {
4154 auto K = MDKindMap.find(Record[I]);
4155 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004156 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00004157 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4158 if (!MD)
4159 return error("Invalid metadata attachment");
4160 F.setMetadata(K->second, MD);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004161 }
4162 continue;
4163 }
4164
4165 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00004166 Instruction *Inst = InstructionList[Record[0]];
4167 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00004168 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00004169 DenseMap<unsigned, unsigned>::iterator I =
4170 MDKindMap.find(Kind);
4171 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004172 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00004173 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004174 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00004175 // Drop the attachment. This used to be legal, but there's no
4176 // upgrade path.
4177 break;
Justin Bognerae341c62016-03-17 20:12:06 +00004178 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4179 if (!MD)
4180 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004181
4182 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4183 MD = upgradeInstructionLoopAttachment(*MD);
4184
Justin Bognerae341c62016-03-17 20:12:06 +00004185 Inst->setMetadata(I->second, MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004186 if (I->second == LLVMContext::MD_tbaa) {
Manman Ren209b17c2013-09-28 00:22:27 +00004187 InstsWithTBAATag.push_back(Inst);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004188 continue;
4189 }
Devang Patelaf206b82009-09-18 19:26:43 +00004190 }
4191 break;
4192 }
4193 }
4194 }
Devang Patelaf206b82009-09-18 19:26:43 +00004195}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004196
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004197static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4198 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004199 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004200 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004201 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4202
4203 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004204 return error(Context, "Explicit load/store type does not match pointee "
4205 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004206 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004207 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004208 return std::error_code();
4209}
4210
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004211/// Lazily parse the specified function body block.
4212std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00004213 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004214 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004215
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004216 // Unexpected unresolved metadata when parsing function.
4217 if (MetadataList.hasFwdRefs())
4218 return error("Invalid function metadata: incoming forward references");
4219
Nick Lewyckya72e1af2010-02-25 08:30:17 +00004220 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00004221 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00004222 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004223
Chris Lattner85b7b402007-05-01 05:52:21 +00004224 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004225 for (Argument &I : F->args())
4226 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004227
Chris Lattner83930552007-05-01 07:01:57 +00004228 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00004229 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00004230 unsigned CurBBNo = 0;
4231
Chris Lattner07d09ed2010-04-03 02:17:50 +00004232 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004233 auto getLastInstruction = [&]() -> Instruction * {
4234 if (CurBB && !CurBB->empty())
4235 return &CurBB->back();
4236 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4237 !FunctionBBs[CurBBNo - 1]->empty())
4238 return &FunctionBBs[CurBBNo - 1]->back();
4239 return nullptr;
4240 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004241
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004242 std::vector<OperandBundleDef> OperandBundles;
4243
Chris Lattner85b7b402007-05-01 05:52:21 +00004244 // Read all the records.
4245 SmallVector<uint64_t, 64> Record;
4246 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00004247 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004248
Chris Lattner27d38752013-01-20 02:13:19 +00004249 switch (Entry.Kind) {
4250 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004251 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004252 case BitstreamEntry::EndBlock:
4253 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004254
Chris Lattner27d38752013-01-20 02:13:19 +00004255 case BitstreamEntry::SubBlock:
4256 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004257 default: // Skip unknown content.
4258 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004259 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004260 break;
4261 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004262 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004263 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004264 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004265 break;
4266 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004267 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004268 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004269 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004270 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004271 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004272 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004273 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004274 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004275 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004276 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004277 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004278 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004279 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004280 return EC;
4281 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004282 }
4283 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004284
Chris Lattner27d38752013-01-20 02:13:19 +00004285 case BitstreamEntry::Record:
4286 // The interesting case.
4287 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004288 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004289
Chris Lattner85b7b402007-05-01 05:52:21 +00004290 // Read a record.
4291 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004292 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004293 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004294 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004295 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004296 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004297 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004298 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004299 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004300 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004301 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004302
4303 // See if anything took the address of blocks in this function.
4304 auto BBFRI = BasicBlockFwdRefs.find(F);
4305 if (BBFRI == BasicBlockFwdRefs.end()) {
4306 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4307 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4308 } else {
4309 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004310 // Check for invalid basic block references.
4311 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004312 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004313 assert(!BBRefs.empty() && "Unexpected empty array");
4314 assert(!BBRefs.front() && "Invalid reference to entry block");
4315 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4316 ++I)
4317 if (I < RE && BBRefs[I]) {
4318 BBRefs[I]->insertInto(F);
4319 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004320 } else {
4321 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4322 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004323
4324 // Erase from the table.
4325 BasicBlockFwdRefs.erase(BBFRI);
4326 }
4327
Chris Lattner83930552007-05-01 07:01:57 +00004328 CurBB = FunctionBBs[0];
4329 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004330 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004331
Chris Lattner07d09ed2010-04-03 02:17:50 +00004332 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4333 // This record indicates that the last instruction is at the same
4334 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004335 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004336
Craig Topper2617dcc2014-04-15 06:32:26 +00004337 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004338 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004339 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004340 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004341 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004342
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004343 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004344 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004345 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004346 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004347
Chris Lattner07d09ed2010-04-03 02:17:50 +00004348 unsigned Line = Record[0], Col = Record[1];
4349 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004350
Craig Topper2617dcc2014-04-15 06:32:26 +00004351 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004352 if (ScopeID) {
4353 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4354 if (!Scope)
4355 return error("Invalid record");
4356 }
4357 if (IAID) {
4358 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4359 if (!IA)
4360 return error("Invalid record");
4361 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004362 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4363 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004364 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004365 continue;
4366 }
4367
Chris Lattnere9759c22007-05-06 00:21:25 +00004368 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4369 unsigned OpNum = 0;
4370 Value *LHS, *RHS;
4371 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004372 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004373 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004374 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004375
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004376 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004377 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004378 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004379 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004380 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004381 if (OpNum < Record.size()) {
4382 if (Opc == Instruction::Add ||
4383 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004384 Opc == Instruction::Mul ||
4385 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004386 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004387 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004388 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004389 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004390 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004391 Opc == Instruction::UDiv ||
4392 Opc == Instruction::LShr ||
4393 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004394 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004395 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004396 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004397 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004398 if (FMF.any())
4399 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004400 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004401
Dan Gohman1b849082009-09-07 23:54:19 +00004402 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004403 break;
4404 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004405 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4406 unsigned OpNum = 0;
4407 Value *Op;
4408 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4409 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004410 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004411
Chris Lattner229907c2011-07-18 04:54:35 +00004412 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004413 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004414 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004415 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004416 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004417 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4418 if (Temp) {
4419 InstructionList.push_back(Temp);
4420 CurBB->getInstList().push_back(Temp);
4421 }
4422 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004423 auto CastOp = (Instruction::CastOps)Opc;
4424 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4425 return error("Invalid cast");
4426 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004427 }
Devang Patelaf206b82009-09-18 19:26:43 +00004428 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004429 break;
4430 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004431 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4432 case bitc::FUNC_CODE_INST_GEP_OLD:
4433 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004434 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004435
4436 Type *Ty;
4437 bool InBounds;
4438
4439 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4440 InBounds = Record[OpNum++];
4441 Ty = getTypeByID(Record[OpNum++]);
4442 } else {
4443 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4444 Ty = nullptr;
4445 }
4446
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004447 Value *BasePtr;
4448 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004449 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004450
David Blaikie60310f22015-05-08 00:42:26 +00004451 if (!Ty)
4452 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4453 ->getElementType();
4454 else if (Ty !=
4455 cast<SequentialType>(BasePtr->getType()->getScalarType())
4456 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004457 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004458 "Explicit gep type does not match pointee type of pointer operand");
4459
Chris Lattner5285b5e2007-05-02 05:46:45 +00004460 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004461 while (OpNum != Record.size()) {
4462 Value *Op;
4463 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004464 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004465 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004466 }
4467
David Blaikie096b1da2015-03-14 19:53:33 +00004468 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004469
Devang Patelaf206b82009-09-18 19:26:43 +00004470 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004471 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004472 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004473 break;
4474 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004475
Dan Gohman1ecaf452008-05-31 00:58:22 +00004476 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4477 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004478 unsigned OpNum = 0;
4479 Value *Agg;
4480 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004481 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004482
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004483 unsigned RecSize = Record.size();
4484 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004485 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004486
Dan Gohman1ecaf452008-05-31 00:58:22 +00004487 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004488 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004489 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004490 bool IsArray = CurTy->isArrayTy();
4491 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004492 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004493
4494 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004495 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004496 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004497 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004498 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004499 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004500 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004501 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004502 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004503
4504 if (IsStruct)
4505 CurTy = CurTy->subtypes()[Index];
4506 else
4507 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004508 }
4509
Jay Foad57aa6362011-07-13 10:26:04 +00004510 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004511 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004512 break;
4513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004514
Dan Gohman1ecaf452008-05-31 00:58:22 +00004515 case bitc::FUNC_CODE_INST_INSERTVAL: {
4516 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004517 unsigned OpNum = 0;
4518 Value *Agg;
4519 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004520 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004521 Value *Val;
4522 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004523 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004524
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004525 unsigned RecSize = Record.size();
4526 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004527 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004528
Dan Gohman1ecaf452008-05-31 00:58:22 +00004529 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004530 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004531 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004532 bool IsArray = CurTy->isArrayTy();
4533 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004534 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004535
4536 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004537 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004538 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004539 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004540 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004541 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004542 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004543 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004544
Dan Gohman1ecaf452008-05-31 00:58:22 +00004545 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004546 if (IsStruct)
4547 CurTy = CurTy->subtypes()[Index];
4548 else
4549 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004550 }
4551
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004552 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004553 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004554
Jay Foad57aa6362011-07-13 10:26:04 +00004555 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004556 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004557 break;
4558 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004559
Chris Lattnere9759c22007-05-06 00:21:25 +00004560 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004561 // obsolete form of select
4562 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004563 unsigned OpNum = 0;
4564 Value *TrueVal, *FalseVal, *Cond;
4565 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004566 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4567 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004568 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004569
Dan Gohmanc5d28922008-09-16 01:01:33 +00004570 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004571 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004572 break;
4573 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004574
Dan Gohmanc5d28922008-09-16 01:01:33 +00004575 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4576 // new form of select
4577 // handles select i1 or select [N x i1]
4578 unsigned OpNum = 0;
4579 Value *TrueVal, *FalseVal, *Cond;
4580 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004581 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004582 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004583 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004584
4585 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004586 if (VectorType* vector_type =
4587 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004588 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004589 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004590 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004591 } else {
4592 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004593 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004594 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004595 }
4596
Gabor Greife9ecc682008-04-06 20:25:17 +00004597 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004598 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004599 break;
4600 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004601
Chris Lattner1fc27f02007-05-02 05:16:49 +00004602 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004603 unsigned OpNum = 0;
4604 Value *Vec, *Idx;
4605 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004606 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004607 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004608 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004609 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004610 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004611 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004612 break;
4613 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004614
Chris Lattner1fc27f02007-05-02 05:16:49 +00004615 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004616 unsigned OpNum = 0;
4617 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004618 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004619 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004620 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004621 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004622 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004623 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004624 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004625 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004626 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004627 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004628 break;
4629 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004630
Chris Lattnere9759c22007-05-06 00:21:25 +00004631 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4632 unsigned OpNum = 0;
4633 Value *Vec1, *Vec2, *Mask;
4634 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004635 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004636 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004637
Mon P Wang25f01062008-11-10 04:46:22 +00004638 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004639 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004640 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004641 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004642 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004643 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004644 break;
4645 }
Mon P Wang25f01062008-11-10 04:46:22 +00004646
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004647 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4648 // Old form of ICmp/FCmp returning bool
4649 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4650 // both legal on vectors but had different behaviour.
4651 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4652 // FCmp/ICmp returning bool or vector of bool
4653
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004654 unsigned OpNum = 0;
4655 Value *LHS, *RHS;
4656 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004657 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4658 return error("Invalid record");
4659
4660 unsigned PredVal = Record[OpNum];
4661 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4662 FastMathFlags FMF;
4663 if (IsFP && Record.size() > OpNum+1)
4664 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4665
4666 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004667 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004668
Duncan Sands9dff9be2010-02-15 16:12:20 +00004669 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004670 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004671 else
James Molloy88eb5352015-07-10 12:52:00 +00004672 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4673
4674 if (FMF.any())
4675 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004676 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004677 break;
4678 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004679
Chris Lattnere53603e2007-05-02 04:27:25 +00004680 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004681 {
4682 unsigned Size = Record.size();
4683 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004684 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004685 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004686 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004687 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004688
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004689 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004690 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004691 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004692 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004693 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004694 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004695
Chris Lattnerf1c87102011-06-17 18:09:11 +00004696 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004697 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004698 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004699 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004700 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004701 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004702 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004703 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004704 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004705 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004706
Devang Patelaf206b82009-09-18 19:26:43 +00004707 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004708 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004709 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004710 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004711 else {
4712 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004713 Value *Cond = getValue(Record, 2, NextValueNo,
4714 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004715 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004716 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004717 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004718 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004719 }
4720 break;
4721 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004722 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004723 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004724 return error("Invalid record");
4725 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004726 Value *CleanupPad =
4727 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004728 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004729 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004730 BasicBlock *UnwindDest = nullptr;
4731 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004732 UnwindDest = getBasicBlock(Record[Idx++]);
4733 if (!UnwindDest)
4734 return error("Invalid record");
4735 }
4736
David Majnemer8a1c45d2015-12-12 05:38:55 +00004737 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004738 InstructionList.push_back(I);
4739 break;
4740 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004741 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4742 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004743 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004744 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004745 Value *CatchPad =
4746 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004747 if (!CatchPad)
4748 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004749 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004750 if (!BB)
4751 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004752
David Majnemer8a1c45d2015-12-12 05:38:55 +00004753 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004754 InstructionList.push_back(I);
4755 break;
4756 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004757 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4758 // We must have, at minimum, the outer scope and the number of arguments.
4759 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004760 return error("Invalid record");
4761
David Majnemer654e1302015-07-31 17:58:14 +00004762 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004763
4764 Value *ParentPad =
4765 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4766
4767 unsigned NumHandlers = Record[Idx++];
4768
4769 SmallVector<BasicBlock *, 2> Handlers;
4770 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4771 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4772 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004773 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004774 Handlers.push_back(BB);
4775 }
4776
4777 BasicBlock *UnwindDest = nullptr;
4778 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004779 UnwindDest = getBasicBlock(Record[Idx++]);
4780 if (!UnwindDest)
4781 return error("Invalid record");
4782 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004783
4784 if (Record.size() != Idx)
4785 return error("Invalid record");
4786
4787 auto *CatchSwitch =
4788 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4789 for (BasicBlock *Handler : Handlers)
4790 CatchSwitch->addHandler(Handler);
4791 I = CatchSwitch;
4792 InstructionList.push_back(I);
4793 break;
4794 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004795 case bitc::FUNC_CODE_INST_CATCHPAD:
4796 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4797 // We must have, at minimum, the outer scope and the number of arguments.
4798 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004799 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004800
David Majnemer654e1302015-07-31 17:58:14 +00004801 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004802
4803 Value *ParentPad =
4804 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4805
David Majnemer654e1302015-07-31 17:58:14 +00004806 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004807
David Majnemer654e1302015-07-31 17:58:14 +00004808 SmallVector<Value *, 2> Args;
4809 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4810 Value *Val;
4811 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4812 return error("Invalid record");
4813 Args.push_back(Val);
4814 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004815
David Majnemer654e1302015-07-31 17:58:14 +00004816 if (Record.size() != Idx)
4817 return error("Invalid record");
4818
David Majnemer8a1c45d2015-12-12 05:38:55 +00004819 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4820 I = CleanupPadInst::Create(ParentPad, Args);
4821 else
4822 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004823 InstructionList.push_back(I);
4824 break;
4825 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004826 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004827 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004828 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004829 // "New" SwitchInst format with case ranges. The changes to write this
4830 // format were reverted but we still recognize bitcode that uses it.
4831 // Hopefully someday we will have support for case ranges and can use
4832 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004833
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004834 Type *OpTy = getTypeByID(Record[1]);
4835 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4836
Jan Wen Voungafaced02012-10-11 20:20:40 +00004837 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004838 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004839 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004840 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004841
4842 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004843
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004844 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4845 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004846
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004847 unsigned CurIdx = 5;
4848 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004849 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004850 unsigned NumItems = Record[CurIdx++];
4851 for (unsigned ci = 0; ci != NumItems; ++ci) {
4852 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004853
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004854 APInt Low;
4855 unsigned ActiveWords = 1;
4856 if (ValueBitWidth > 64)
4857 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004858 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004859 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004860 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004861
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004862 if (!isSingleNumber) {
4863 ActiveWords = 1;
4864 if (ValueBitWidth > 64)
4865 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004866 APInt High = readWideAPInt(
4867 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004868 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004869
4870 // FIXME: It is not clear whether values in the range should be
4871 // compared as signed or unsigned values. The partially
4872 // implemented changes that used this format in the past used
4873 // unsigned comparisons.
4874 for ( ; Low.ule(High); ++Low)
4875 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004876 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004877 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004878 }
4879 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004880 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4881 cve = CaseVals.end(); cvi != cve; ++cvi)
4882 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004883 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004884 I = SI;
4885 break;
4886 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004887
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004888 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004889
Chris Lattner5285b5e2007-05-02 05:46:45 +00004890 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004891 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004892 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004893 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004894 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004895 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004896 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004897 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004898 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004899 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004900 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004901 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004902 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4903 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004904 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004905 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004906 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004907 }
4908 SI->addCase(CaseVal, DestBB);
4909 }
4910 I = SI;
4911 break;
4912 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004913 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004914 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004915 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004916 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004917 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004918 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004919 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004920 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004921 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004922 InstructionList.push_back(IBI);
4923 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4924 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4925 IBI->addDestination(DestBB);
4926 } else {
4927 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004928 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004929 }
4930 }
4931 I = IBI;
4932 break;
4933 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004934
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004935 case bitc::FUNC_CODE_INST_INVOKE: {
4936 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004937 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004938 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004939 unsigned OpNum = 0;
4940 AttributeSet PAL = getAttributes(Record[OpNum++]);
4941 unsigned CCInfo = Record[OpNum++];
4942 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4943 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004944
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004945 FunctionType *FTy = nullptr;
4946 if (CCInfo >> 13 & 1 &&
4947 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004948 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004949
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004950 Value *Callee;
4951 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004952 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004953
Chris Lattner229907c2011-07-18 04:54:35 +00004954 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004955 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004956 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004957 if (!FTy) {
4958 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4959 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004960 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004961 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004962 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004963 "callee operand");
4964 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004965 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004966
Chris Lattner5285b5e2007-05-02 05:46:45 +00004967 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004968 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004969 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4970 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004971 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004972 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004973 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004974
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004975 if (!FTy->isVarArg()) {
4976 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004977 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004978 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004979 // Read type/value pairs for varargs params.
4980 while (OpNum != Record.size()) {
4981 Value *Op;
4982 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004983 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004984 Ops.push_back(Op);
4985 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004986 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004987
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004988 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4989 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004990 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004991 cast<InvokeInst>(I)->setCallingConv(
4992 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004993 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004994 break;
4995 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004996 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4997 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004998 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004999 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005000 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00005001 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00005002 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005003 break;
5004 }
Chris Lattnere53603e2007-05-02 04:27:25 +00005005 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00005006 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00005007 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00005008 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00005009 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00005010 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005011 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005012 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005013 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005014 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005015
Jay Foad52131342011-03-30 11:28:46 +00005016 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00005017 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005018
Chris Lattnere14cb882007-05-04 19:11:41 +00005019 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005020 Value *V;
5021 // With the new function encoding, it is possible that operands have
5022 // negative IDs (for forward references). Use a signed VBR
5023 // representation to keep the encoding small.
5024 if (UseRelativeIDs)
5025 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5026 else
5027 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00005028 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005029 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005030 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00005031 PN->addIncoming(V, BB);
5032 }
5033 I = PN;
5034 break;
5035 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005036
David Majnemer7fddecc2015-06-17 20:52:32 +00005037 case bitc::FUNC_CODE_INST_LANDINGPAD:
5038 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00005039 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5040 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00005041 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5042 if (Record.size() < 3)
5043 return error("Invalid record");
5044 } else {
5045 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5046 if (Record.size() < 4)
5047 return error("Invalid record");
5048 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005049 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005050 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005051 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00005052 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5053 Value *PersFn = nullptr;
5054 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5055 return error("Invalid record");
5056
5057 if (!F->hasPersonalityFn())
5058 F->setPersonalityFn(cast<Constant>(PersFn));
5059 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5060 return error("Personality function mismatch");
5061 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005062
5063 bool IsCleanup = !!Record[Idx++];
5064 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00005065 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00005066 LP->setCleanup(IsCleanup);
5067 for (unsigned J = 0; J != NumClauses; ++J) {
5068 LandingPadInst::ClauseType CT =
5069 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5070 Value *Val;
5071
5072 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5073 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005074 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00005075 }
5076
5077 assert((CT != LandingPadInst::Catch ||
5078 !isa<ArrayType>(Val->getType())) &&
5079 "Catch clause has a invalid type!");
5080 assert((CT != LandingPadInst::Filter ||
5081 isa<ArrayType>(Val->getType())) &&
5082 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005083 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00005084 }
5085
5086 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00005087 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00005088 break;
5089 }
5090
Chris Lattnerf1c87102011-06-17 18:09:11 +00005091 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5092 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005093 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00005094 uint64_t AlignRecord = Record[3];
5095 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00005096 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005097 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5098 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5099 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00005100 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005101 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00005102 Type *Ty = getTypeByID(Record[0]);
5103 if ((AlignRecord & ExplicitTypeMask) == 0) {
5104 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5105 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005106 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00005107 Ty = PTy->getElementType();
5108 }
5109 Type *OpTy = getTypeByID(Record[1]);
5110 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00005111 unsigned Align;
5112 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00005113 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00005114 return EC;
5115 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00005116 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005117 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00005118 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005119 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005120 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005121 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00005122 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00005123 break;
5124 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005125 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005126 unsigned OpNum = 0;
5127 Value *Op;
5128 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005129 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005130 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00005131
5132 Type *Ty = nullptr;
5133 if (OpNum + 3 == Record.size())
5134 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005135 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005136 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005137 if (!Ty)
5138 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005139
JF Bastien30bf96b2015-02-22 19:32:03 +00005140 unsigned Align;
5141 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5142 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005143 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00005144
Devang Patelaf206b82009-09-18 19:26:43 +00005145 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00005146 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00005147 }
Eli Friedman59b66882011-08-09 23:02:53 +00005148 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5149 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5150 unsigned OpNum = 0;
5151 Value *Op;
5152 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005153 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005154 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005155
David Blaikie85035652015-02-25 01:07:20 +00005156 Type *Ty = nullptr;
5157 if (OpNum + 5 == Record.size())
5158 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005159 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005160 return EC;
5161 if (!Ty)
5162 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005163
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005164 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005165 if (Ordering == AtomicOrdering::NotAtomic ||
5166 Ordering == AtomicOrdering::Release ||
5167 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005168 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00005169 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005170 return error("Invalid record");
5171 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00005172
JF Bastien30bf96b2015-02-22 19:32:03 +00005173 unsigned Align;
5174 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5175 return EC;
5176 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00005177
Eli Friedman59b66882011-08-09 23:02:53 +00005178 InstructionList.push_back(I);
5179 break;
5180 }
David Blaikie612ddbf2015-04-22 04:14:42 +00005181 case bitc::FUNC_CODE_INST_STORE:
5182 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005183 unsigned OpNum = 0;
5184 Value *Val, *Ptr;
5185 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00005186 (BitCode == bitc::FUNC_CODE_INST_STORE
5187 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5188 : popValue(Record, OpNum, NextValueNo,
5189 cast<PointerType>(Ptr->getType())->getElementType(),
5190 Val)) ||
5191 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005192 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005193
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005194 if (std::error_code EC =
5195 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005196 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00005197 unsigned Align;
5198 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5199 return EC;
5200 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00005201 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005202 break;
5203 }
David Blaikie50a06152015-04-22 04:14:46 +00005204 case bitc::FUNC_CODE_INST_STOREATOMIC:
5205 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00005206 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5207 unsigned OpNum = 0;
5208 Value *Val, *Ptr;
5209 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00005210 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5211 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5212 : popValue(Record, OpNum, NextValueNo,
5213 cast<PointerType>(Ptr->getType())->getElementType(),
5214 Val)) ||
5215 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005216 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005217
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005218 if (std::error_code EC =
5219 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005220 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005221 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005222 if (Ordering == AtomicOrdering::NotAtomic ||
5223 Ordering == AtomicOrdering::Acquire ||
5224 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005225 return error("Invalid record");
5226 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00005227 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005228 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005229
JF Bastien30bf96b2015-02-22 19:32:03 +00005230 unsigned Align;
5231 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5232 return EC;
5233 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00005234 InstructionList.push_back(I);
5235 break;
5236 }
David Blaikie2a661cd2015-04-28 04:30:29 +00005237 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005238 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00005239 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00005240 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005241 unsigned OpNum = 0;
5242 Value *Ptr, *Cmp, *New;
5243 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005244 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5245 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5246 : popValue(Record, OpNum, NextValueNo,
5247 cast<PointerType>(Ptr->getType())->getElementType(),
5248 Cmp)) ||
5249 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5250 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005251 return error("Invalid record");
5252 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00005253 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5254 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005255 return error("Invalid record");
5256 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005257
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005258 if (std::error_code EC =
5259 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005260 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005261 AtomicOrdering FailureOrdering;
5262 if (Record.size() < 7)
5263 FailureOrdering =
5264 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5265 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005266 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005267
5268 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5269 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005270 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005271
5272 if (Record.size() < 8) {
5273 // Before weak cmpxchgs existed, the instruction simply returned the
5274 // value loaded from memory, so bitcode files from that era will be
5275 // expecting the first component of a modern cmpxchg.
5276 CurBB->getInstList().push_back(I);
5277 I = ExtractValueInst::Create(I, 0);
5278 } else {
5279 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5280 }
5281
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005282 InstructionList.push_back(I);
5283 break;
5284 }
5285 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5286 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5287 unsigned OpNum = 0;
5288 Value *Ptr, *Val;
5289 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005290 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005291 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5292 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005293 return error("Invalid record");
5294 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005295 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5296 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005297 return error("Invalid record");
5298 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005299 if (Ordering == AtomicOrdering::NotAtomic ||
5300 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005301 return error("Invalid record");
5302 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005303 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5304 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5305 InstructionList.push_back(I);
5306 break;
5307 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005308 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5309 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005310 return error("Invalid record");
5311 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00005312 if (Ordering == AtomicOrdering::NotAtomic ||
5313 Ordering == AtomicOrdering::Unordered ||
5314 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005315 return error("Invalid record");
5316 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005317 I = new FenceInst(Context, Ordering, SynchScope);
5318 InstructionList.push_back(I);
5319 break;
5320 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005321 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005322 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005323 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005324 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005325
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005326 unsigned OpNum = 0;
5327 AttributeSet PAL = getAttributes(Record[OpNum++]);
5328 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005329
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005330 FastMathFlags FMF;
5331 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5332 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5333 if (!FMF.any())
5334 return error("Fast math flags indicator set for call with no FMF");
5335 }
5336
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005337 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005338 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005339 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005340 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005341
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005342 Value *Callee;
5343 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005344 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005345
Chris Lattner229907c2011-07-18 04:54:35 +00005346 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005347 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005348 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005349 if (!FTy) {
5350 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5351 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005352 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005353 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005354 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005355 "callee operand");
5356 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005357 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005358
Chris Lattner9f600c52007-05-03 22:04:19 +00005359 SmallVector<Value*, 16> Args;
5360 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005361 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005362 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005363 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005364 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005365 Args.push_back(getValue(Record, OpNum, NextValueNo,
5366 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005367 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005368 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005369 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005370
Chris Lattner9f600c52007-05-03 22:04:19 +00005371 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005372 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005373 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005374 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005375 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005376 while (OpNum != Record.size()) {
5377 Value *Op;
5378 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005379 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005380 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005381 }
5382 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005383
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005384 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5385 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005386 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005387 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005388 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005389 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005390 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005391 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005392 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005393 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005394 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005395 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005396 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005397 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005398 if (FMF.any()) {
5399 if (!isa<FPMathOperator>(I))
5400 return error("Fast-math-flags specified for call without "
5401 "floating-point scalar or vector return type");
5402 I->setFastMathFlags(FMF);
5403 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005404 break;
5405 }
5406 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5407 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005408 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005409 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005410 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005411 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005412 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005413 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005414 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005415 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005416 break;
5417 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005418
5419 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5420 // A call or an invoke can be optionally prefixed with some variable
5421 // number of operand bundle blocks. These blocks are read into
5422 // OperandBundles and consumed at the next call or invoke instruction.
5423
5424 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5425 return error("Invalid record");
5426
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005427 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005428
5429 unsigned OpNum = 1;
5430 while (OpNum != Record.size()) {
5431 Value *Op;
5432 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5433 return error("Invalid record");
5434 Inputs.push_back(Op);
5435 }
5436
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005437 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005438 continue;
5439 }
Chris Lattner83930552007-05-01 07:01:57 +00005440 }
5441
5442 // Add instruction to end of current BB. If there is no current BB, reject
5443 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005444 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005445 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005446 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005447 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005448 if (!OperandBundles.empty()) {
5449 delete I;
5450 return error("Operand bundles found with no consumer");
5451 }
Chris Lattner83930552007-05-01 07:01:57 +00005452 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005453
Chris Lattner83930552007-05-01 07:01:57 +00005454 // If this was a terminator instruction, move to the next block.
5455 if (isa<TerminatorInst>(I)) {
5456 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005457 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005458 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005459
Chris Lattner83930552007-05-01 07:01:57 +00005460 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005461 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005462 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005463 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005464
Chris Lattner27d38752013-01-20 02:13:19 +00005465OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005466
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005467 if (!OperandBundles.empty())
5468 return error("Operand bundles found with no consumer");
5469
Chris Lattner83930552007-05-01 07:01:57 +00005470 // Check the function list for unresolved values.
5471 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005472 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005473 // We found at least one unresolved value. Nuke them all to avoid leaks.
5474 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005475 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005476 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005477 delete A;
5478 }
5479 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005480 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005481 }
Chris Lattner83930552007-05-01 07:01:57 +00005482 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005483
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00005484 // Unexpected unresolved metadata about to be dropped.
5485 if (MetadataList.hasFwdRefs())
5486 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00005487
Chris Lattner85b7b402007-05-01 05:52:21 +00005488 // Trim the value list down to the size it was before we parsed this function.
5489 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005490 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005491 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005492 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005493}
5494
Rafael Espindola7d712032013-11-05 17:16:08 +00005495/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005496std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005497 Function *F,
5498 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005499 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005500 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005501 // didn't contain the function index in the VST, or when we have
5502 // an anonymous function which would not have a VST entry.
5503 // Assert that we have one of those two cases.
5504 assert(VSTOffset == 0 || !F->hasName());
5505 // Parse the next body in the stream and set its position in the
5506 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005507 if (std::error_code EC = rememberAndSkipFunctionBodies())
5508 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005509 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005510 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005511}
5512
Chris Lattner9eeada92007-05-18 04:02:46 +00005513//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005514// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005515//===----------------------------------------------------------------------===//
5516
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005517void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005518
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005519std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Duncan P. N. Exon Smith68f56242016-03-25 01:29:50 +00005520 if (std::error_code EC = materializeMetadata())
5521 return EC;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005522
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005523 Function *F = dyn_cast<Function>(GV);
5524 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005525 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005526 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005527
5528 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005529 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005530 // If its position is recorded as 0, its body is somewhere in the stream
5531 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005532 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005533 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005534 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005535
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005536 // Move the bit stream to the saved position of the deferred function body.
5537 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005538
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005539 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005540 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005541 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005542
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005543 if (StripDebugInfo)
5544 stripDebugInfo(*F);
5545
Chandler Carruth7132e002007-08-04 01:51:18 +00005546 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005547 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005548 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5549 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005550 User *U = *UI;
5551 ++UI;
5552 if (CallInst *CI = dyn_cast<CallInst>(U))
5553 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005554 }
5555 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005556
Peter Collingbourned4bff302015-11-05 22:03:56 +00005557 // Finish fn->subprogram upgrade for materialized functions.
5558 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5559 F->setSubprogram(SP);
5560
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005561 // Bring in any functions that this function forward-referenced via
5562 // blockaddresses.
5563 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005564}
5565
Rafael Espindola79753a02015-12-18 21:18:57 +00005566std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005567 if (std::error_code EC = materializeMetadata())
5568 return EC;
5569
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005570 // Promise to materialize all forward references.
5571 WillMaterializeAllForwardRefs = true;
5572
Chris Lattner06310bf2009-06-16 05:15:21 +00005573 // Iterate over the module, deserializing any functions that are still on
5574 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005575 for (Function &F : *TheModule) {
5576 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005577 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005578 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005579 // At this point, if there are any function bodies, parse the rest of
5580 // the bits in the module past the last function block we have recorded
5581 // through either lazy scanning or the VST.
5582 if (LastFunctionBlockBit || NextUnreadBit)
5583 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5584 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005585
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005586 // Check that all block address forward references got resolved (as we
5587 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005588 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005589 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005590
Chris Bieneman671d0dd2016-03-16 23:17:54 +00005591 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5592 // to prevent this instructions with TBAA tags should be upgraded first.
5593 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5594 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5595
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005596 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5597 // delete the old functions to clean up. We can't do this unless the entire
5598 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005599 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005600 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005601 for (auto *U : I.first->users()) {
5602 if (CallInst *CI = dyn_cast<CallInst>(U))
5603 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005604 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005605 if (!I.first->use_empty())
5606 I.first->replaceAllUsesWith(I.second);
5607 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005608 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005609 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005610
Rafael Espindola79753a02015-12-18 21:18:57 +00005611 UpgradeDebugInfo(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005612 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005613}
5614
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005615std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5616 return IdentifiedStructTypes;
5617}
5618
Rafael Espindola1aabf982015-06-16 23:29:49 +00005619std::error_code
5620BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005621 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005622 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005623 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005624}
5625
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005626std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005627 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005628 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5629
Rafael Espindola27435252014-07-29 21:01:24 +00005630 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005631 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005632
5633 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5634 // The magic number is 0x0B17C0DE stored in little endian.
5635 if (isBitcodeWrapper(BufPtr, BufEnd))
5636 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005637 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005638
5639 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005640 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005641
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005642 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005643}
5644
Rafael Espindola1aabf982015-06-16 23:29:49 +00005645std::error_code
5646BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005647 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5648 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005649 auto OwnedBytes =
5650 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005651 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005652 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005653 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005654
5655 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005656 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005657 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005658
5659 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005660 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005661
5662 if (isBitcodeWrapper(buf, buf + 4)) {
5663 const unsigned char *bitcodeStart = buf;
5664 const unsigned char *bitcodeEnd = buf + 16;
5665 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005666 Bytes.dropLeadingBytes(bitcodeStart - buf);
5667 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005668 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005669 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005670}
5671
Teresa Johnson26ab5772016-03-15 00:04:37 +00005672std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E,
5673 const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005674 return ::error(DiagnosticHandler, make_error_code(E), Message);
5675}
5676
Teresa Johnson26ab5772016-03-15 00:04:37 +00005677std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005678 return ::error(DiagnosticHandler,
5679 make_error_code(BitcodeError::CorruptedBitcode), Message);
5680}
5681
Teresa Johnson26ab5772016-03-15 00:04:37 +00005682std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005683 return ::error(DiagnosticHandler, make_error_code(E));
5684}
5685
Teresa Johnson26ab5772016-03-15 00:04:37 +00005686ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005687 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005688 bool CheckGlobalValSummaryPresenceOnly)
5689 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005690 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005691
Teresa Johnson26ab5772016-03-15 00:04:37 +00005692ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005693 DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005694 bool CheckGlobalValSummaryPresenceOnly)
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005695 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005696 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005697
Teresa Johnson26ab5772016-03-15 00:04:37 +00005698void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
Teresa Johnson403a7872015-10-04 14:33:43 +00005699
Teresa Johnson26ab5772016-03-15 00:04:37 +00005700void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
Teresa Johnson403a7872015-10-04 14:33:43 +00005701
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005702GlobalValue::GUID
5703ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005704 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5705 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5706 return VGI->second;
5707}
5708
5709GlobalValueInfo *
Teresa Johnson26ab5772016-03-15 00:04:37 +00005710ModuleSummaryIndexBitcodeReader::getInfoFromSummaryOffset(uint64_t Offset) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005711 auto I = SummaryOffsetToInfoMap.find(Offset);
5712 assert(I != SummaryOffsetToInfoMap.end());
5713 return I->second;
5714}
5715
5716// Specialized value symbol table parser used when reading module index
Teresa Johnson403a7872015-10-04 14:33:43 +00005717// blocks where we don't actually create global values.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005718// At the end of this routine the module index is populated with a map
5719// from global value name to GlobalValueInfo. The global value info contains
5720// the function block's bitcode offset (if applicable), or the offset into the
5721// summary section for the combined index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005722std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005723 uint64_t Offset,
5724 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5725 assert(Offset > 0 && "Expected non-zero VST offset");
5726 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5727
Teresa Johnson403a7872015-10-04 14:33:43 +00005728 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5729 return error("Invalid record");
5730
5731 SmallVector<uint64_t, 64> Record;
5732
5733 // Read all the records for this value table.
5734 SmallString<128> ValueName;
5735 while (1) {
5736 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5737
5738 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005739 case BitstreamEntry::SubBlock: // Handled for us already.
5740 case BitstreamEntry::Error:
5741 return error("Malformed block");
5742 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005743 // Done parsing VST, jump back to wherever we came from.
5744 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005745 return std::error_code();
5746 case BitstreamEntry::Record:
5747 // The interesting case.
5748 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005749 }
5750
5751 // Read a record.
5752 Record.clear();
5753 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005754 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5755 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005756 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5757 if (convertToString(Record, 1, ValueName))
5758 return error("Invalid record");
5759 unsigned ValueID = Record[0];
5760 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5761 llvm::make_unique<GlobalValueInfo>();
5762 assert(!SourceFileName.empty());
5763 auto VLI = ValueIdToLinkageMap.find(ValueID);
5764 assert(VLI != ValueIdToLinkageMap.end() &&
5765 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005766 std::string GlobalId = GlobalValue::getGlobalIdentifier(
5767 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005768 auto ValueGUID = GlobalValue::getGUID(GlobalId);
5769 if (PrintSummaryGUIDs)
5770 dbgs() << "GUID " << ValueGUID << " is " << ValueName << "\n";
5771 TheIndex->addGlobalValueInfo(ValueGUID, std::move(GlobalValInfo));
5772 ValueIdToCallGraphGUIDMap[ValueID] = ValueGUID;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005773 ValueName.clear();
5774 break;
5775 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005776 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005777 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005778 if (convertToString(Record, 2, ValueName))
5779 return error("Invalid record");
5780 unsigned ValueID = Record[0];
5781 uint64_t FuncOffset = Record[1];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005782 std::unique_ptr<GlobalValueInfo> FuncInfo =
5783 llvm::make_unique<GlobalValueInfo>(FuncOffset);
5784 assert(!SourceFileName.empty());
5785 auto VLI = ValueIdToLinkageMap.find(ValueID);
5786 assert(VLI != ValueIdToLinkageMap.end() &&
5787 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005788 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5789 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005790 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
5791 if (PrintSummaryGUIDs)
5792 dbgs() << "GUID " << FunctionGUID << " is " << ValueName << "\n";
5793 TheIndex->addGlobalValueInfo(FunctionGUID, std::move(FuncInfo));
5794 ValueIdToCallGraphGUIDMap[ValueID] = FunctionGUID;
Teresa Johnson403a7872015-10-04 14:33:43 +00005795
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005796 ValueName.clear();
5797 break;
5798 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005799 case bitc::VST_CODE_COMBINED_GVDEFENTRY: {
5800 // VST_CODE_COMBINED_GVDEFENTRY: [valueid, offset, guid]
5801 unsigned ValueID = Record[0];
5802 uint64_t GlobalValSummaryOffset = Record[1];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005803 GlobalValue::GUID GlobalValGUID = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005804 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5805 llvm::make_unique<GlobalValueInfo>(GlobalValSummaryOffset);
5806 SummaryOffsetToInfoMap[GlobalValSummaryOffset] = GlobalValInfo.get();
5807 TheIndex->addGlobalValueInfo(GlobalValGUID, std::move(GlobalValInfo));
5808 ValueIdToCallGraphGUIDMap[ValueID] = GlobalValGUID;
5809 break;
5810 }
5811 case bitc::VST_CODE_COMBINED_ENTRY: {
5812 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5813 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005814 GlobalValue::GUID RefGUID = Record[1];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005815 ValueIdToCallGraphGUIDMap[ValueID] = RefGUID;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005816 break;
5817 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005818 }
5819 }
5820}
5821
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005822// Parse just the blocks needed for building the index out of the module.
5823// At the end of this routine the module Index is populated with a map
5824// from global value name to GlobalValueInfo. The global value info contains
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005825// the parsed summary information (when parsing summaries eagerly).
Teresa Johnson26ab5772016-03-15 00:04:37 +00005826std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005827 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5828 return error("Invalid record");
5829
Teresa Johnsone1164de2016-02-10 21:55:02 +00005830 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005831 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5832 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005833
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005834 // Read the index for this module.
Teresa Johnson403a7872015-10-04 14:33:43 +00005835 while (1) {
5836 BitstreamEntry Entry = Stream.advance();
5837
5838 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005839 case BitstreamEntry::Error:
5840 return error("Malformed block");
5841 case BitstreamEntry::EndBlock:
5842 return std::error_code();
5843
5844 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005845 if (CheckGlobalValSummaryPresenceOnly) {
5846 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5847 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005848 // No need to parse the rest since we found the summary.
5849 return std::error_code();
5850 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005851 if (Stream.SkipBlock())
5852 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005853 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005854 }
5855 switch (Entry.ID) {
5856 default: // Skip unknown content.
5857 if (Stream.SkipBlock())
5858 return error("Invalid record");
5859 break;
5860 case bitc::BLOCKINFO_BLOCK_ID:
5861 // Need to parse these to get abbrev ids (e.g. for VST)
5862 if (Stream.ReadBlockInfoBlock())
5863 return error("Malformed block");
5864 break;
5865 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005866 // Should have been parsed earlier via VSTOffset, unless there
5867 // is no summary section.
5868 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5869 !SeenGlobalValSummary) &&
5870 "Expected early VST parse via VSTOffset record");
5871 if (Stream.SkipBlock())
5872 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005873 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005874 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5875 assert(VSTOffset > 0 && "Expected non-zero VST offset");
5876 assert(!SeenValueSymbolTable &&
5877 "Already read VST when parsing summary block?");
5878 if (std::error_code EC =
5879 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5880 return EC;
5881 SeenValueSymbolTable = true;
5882 SeenGlobalValSummary = true;
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005883 if (std::error_code EC = parseEntireSummary())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005884 return EC;
5885 break;
5886 case bitc::MODULE_STRTAB_BLOCK_ID:
5887 if (std::error_code EC = parseModuleStringTable())
5888 return EC;
5889 break;
5890 }
5891 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005892
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005893 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005894 Record.clear();
5895 auto BitCode = Stream.readRecord(Entry.ID, Record);
5896 switch (BitCode) {
5897 default:
5898 break; // Default behavior, ignore unknown content.
5899 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005900 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005901 SmallString<128> ValueName;
5902 if (convertToString(Record, 0, ValueName))
5903 return error("Invalid record");
5904 SourceFileName = ValueName.c_str();
5905 break;
5906 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005907 /// MODULE_CODE_HASH: [5*i32]
5908 case bitc::MODULE_CODE_HASH: {
5909 if (Record.size() != 5)
5910 return error("Invalid hash length " + Twine(Record.size()).str());
5911 if (!TheIndex)
5912 break;
5913 if (TheIndex->modulePaths().empty())
5914 // Does not have any summary emitted.
5915 break;
5916 if (TheIndex->modulePaths().size() != 1)
5917 return error("Don't expect multiple modules defined?");
5918 auto &Hash = TheIndex->modulePaths().begin()->second.second;
5919 int Pos = 0;
5920 for (auto &Val : Record) {
5921 assert(!(Val >> 32) && "Unexpected high bits set");
5922 Hash[Pos++] = Val;
5923 }
5924 break;
5925 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005926 /// MODULE_CODE_VSTOFFSET: [offset]
5927 case bitc::MODULE_CODE_VSTOFFSET:
5928 if (Record.size() < 1)
5929 return error("Invalid record");
5930 VSTOffset = Record[0];
5931 break;
5932 // GLOBALVAR: [pointer type, isconst, initid,
5933 // linkage, alignment, section, visibility, threadlocal,
5934 // unnamed_addr, externally_initialized, dllstorageclass,
5935 // comdat]
5936 case bitc::MODULE_CODE_GLOBALVAR: {
5937 if (Record.size() < 6)
5938 return error("Invalid record");
5939 uint64_t RawLinkage = Record[3];
5940 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5941 ValueIdToLinkageMap[ValueId++] = Linkage;
5942 break;
5943 }
5944 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
5945 // alignment, section, visibility, gc, unnamed_addr,
5946 // prologuedata, dllstorageclass, comdat, prefixdata]
5947 case bitc::MODULE_CODE_FUNCTION: {
5948 if (Record.size() < 8)
5949 return error("Invalid record");
5950 uint64_t RawLinkage = Record[3];
5951 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5952 ValueIdToLinkageMap[ValueId++] = Linkage;
5953 break;
5954 }
5955 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
5956 // dllstorageclass]
5957 case bitc::MODULE_CODE_ALIAS: {
5958 if (Record.size() < 6)
5959 return error("Invalid record");
5960 uint64_t RawLinkage = Record[3];
5961 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5962 ValueIdToLinkageMap[ValueId++] = Linkage;
5963 break;
5964 }
5965 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005966 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005967 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005968 }
5969 }
5970}
5971
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005972// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5973// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005974std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005975 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00005976 return error("Invalid record");
5977
5978 SmallVector<uint64_t, 64> Record;
5979
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005980 bool Combined = false;
Teresa Johnson403a7872015-10-04 14:33:43 +00005981 while (1) {
5982 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5983
5984 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005985 case BitstreamEntry::SubBlock: // Handled for us already.
5986 case BitstreamEntry::Error:
5987 return error("Malformed block");
5988 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005989 // For a per-module index, remove any entries that still have empty
5990 // summaries. The VST parsing creates entries eagerly for all symbols,
5991 // but not all have associated summaries (e.g. it doesn't know how to
5992 // distinguish between VST_CODE_ENTRY for function declarations vs global
5993 // variables with initializers that end up with a summary). Remove those
5994 // entries now so that we don't need to rely on the combined index merger
5995 // to clean them up (especially since that may not run for the first
5996 // module's index if we merge into that).
5997 if (!Combined)
5998 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005999 return std::error_code();
6000 case BitstreamEntry::Record:
6001 // The interesting case.
6002 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006003 }
6004
6005 // Read a record. The record format depends on whether this
6006 // is a per-module index or a combined index file. In the per-module
6007 // case the records contain the associated value's ID for correlation
6008 // with VST entries. In the combined index the correlation is done
6009 // via the bitcode offset of the summary records (which were saved
6010 // in the combined index VST entries). The records also contain
6011 // information used for ThinLTO renaming and importing.
6012 Record.clear();
6013 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006014 auto BitCode = Stream.readRecord(Entry.ID, Record);
6015 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006016 default: // Default behavior: ignore.
6017 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006018 // FS_PERMODULE: [valueid, linkage, instcount, numrefs, numrefs x valueid,
6019 // n x (valueid, callsitecount)]
6020 // FS_PERMODULE_PROFILE: [valueid, linkage, instcount, numrefs,
6021 // numrefs x valueid,
6022 // n x (valueid, callsitecount, profilecount)]
6023 case bitc::FS_PERMODULE:
6024 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006025 unsigned ValueID = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00006026 uint64_t RawLinkage = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006027 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006028 unsigned NumRefs = Record[3];
6029 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
6030 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006031 // The module path string ref set in the summary must be owned by the
6032 // index's module string table. Since we don't have a module path
6033 // string table section in the per-module index, we create a single
6034 // module path string table entry with an empty (0) ID to take
6035 // ownership.
6036 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006037 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006038 static int RefListStartIndex = 4;
6039 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6040 assert(Record.size() >= RefListStartIndex + NumRefs &&
6041 "Record size inconsistent with number of references");
6042 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6043 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006044 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006045 FS->addRefEdge(RefGUID);
6046 }
6047 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6048 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6049 ++I) {
6050 unsigned CalleeValueId = Record[I];
6051 unsigned CallsiteCount = Record[++I];
6052 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006053 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006054 FS->addCallGraphEdge(CalleeGUID,
6055 CalleeInfo(CallsiteCount, ProfileCount));
6056 }
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006057 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
Teresa Johnsonfb7c7642016-04-05 00:40:16 +00006058 auto *Info = TheIndex->getGlobalValueInfo(GUID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006059 assert(!Info->summary() && "Expected a single summary per VST entry");
6060 Info->setSummary(std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006061 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006062 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006063 // FS_ALIAS: [valueid, linkage, valueid]
6064 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6065 // they expect all aliasee summaries to be available.
6066 case bitc::FS_ALIAS: {
6067 unsigned ValueID = Record[0];
6068 uint64_t RawLinkage = Record[1];
6069 unsigned AliaseeID = Record[2];
6070 std::unique_ptr<AliasSummary> AS =
6071 llvm::make_unique<AliasSummary>(getDecodedLinkage(RawLinkage));
6072 // The module path string ref set in the summary must be owned by the
6073 // index's module string table. Since we don't have a module path
6074 // string table section in the per-module index, we create a single
6075 // module path string table entry with an empty (0) ID to take
6076 // ownership.
6077 AS->setModulePath(
6078 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6079
6080 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID);
6081 auto *AliaseeInfo = TheIndex->getGlobalValueInfo(AliaseeGUID);
6082 if (!AliaseeInfo->summary())
6083 return error("Alias expects aliasee summary to be parsed");
6084 AS->setAliasee(AliaseeInfo->summary());
6085
6086 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
6087 auto *Info = TheIndex->getGlobalValueInfo(GUID);
6088 assert(!Info->summary() && "Expected a single summary per VST entry");
6089 Info->setSummary(std::move(AS));
6090 break;
6091 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006092 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, linkage, n x valueid]
6093 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6094 unsigned ValueID = Record[0];
6095 uint64_t RawLinkage = Record[1];
6096 std::unique_ptr<GlobalVarSummary> FS =
6097 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
6098 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006099 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006100 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6101 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006102 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006103 FS->addRefEdge(RefGUID);
6104 }
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006105 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
Teresa Johnsonfb7c7642016-04-05 00:40:16 +00006106 auto *Info = TheIndex->getGlobalValueInfo(GUID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006107 assert(!Info->summary() && "Expected a single summary per VST entry");
6108 Info->setSummary(std::move(FS));
6109 break;
6110 }
6111 // FS_COMBINED: [modid, linkage, instcount, numrefs, numrefs x valueid,
6112 // n x (valueid, callsitecount)]
6113 // FS_COMBINED_PROFILE: [modid, linkage, instcount, numrefs,
6114 // numrefs x valueid,
6115 // n x (valueid, callsitecount, profilecount)]
6116 case bitc::FS_COMBINED:
6117 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006118 uint64_t ModuleId = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00006119 uint64_t RawLinkage = Record[1];
6120 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006121 unsigned NumRefs = Record[3];
6122 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
6123 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006124 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006125 static int RefListStartIndex = 4;
6126 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6127 assert(Record.size() >= RefListStartIndex + NumRefs &&
6128 "Record size inconsistent with number of references");
6129 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6130 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006131 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006132 FS->addRefEdge(RefGUID);
6133 }
6134 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6135 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6136 ++I) {
6137 unsigned CalleeValueId = Record[I];
6138 unsigned CallsiteCount = Record[++I];
6139 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006140 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006141 FS->addCallGraphEdge(CalleeGUID,
6142 CalleeInfo(CallsiteCount, ProfileCount));
6143 }
6144 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
6145 assert(!Info->summary() && "Expected a single summary per VST entry");
6146 Info->setSummary(std::move(FS));
6147 Combined = true;
6148 break;
6149 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006150 // FS_COMBINED_ALIAS: [modid, linkage, offset]
6151 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6152 // they expect all aliasee summaries to be available.
6153 case bitc::FS_COMBINED_ALIAS: {
6154 uint64_t ModuleId = Record[0];
6155 uint64_t RawLinkage = Record[1];
6156 uint64_t AliaseeSummaryOffset = Record[2];
6157 std::unique_ptr<AliasSummary> AS =
6158 llvm::make_unique<AliasSummary>(getDecodedLinkage(RawLinkage));
6159 AS->setModulePath(ModuleIdMap[ModuleId]);
6160
6161 auto *AliaseeInfo = getInfoFromSummaryOffset(AliaseeSummaryOffset);
6162 if (!AliaseeInfo->summary())
6163 return error("Alias expects aliasee summary to be parsed");
6164 AS->setAliasee(AliaseeInfo->summary());
6165
6166 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
6167 assert(!Info->summary() && "Expected a single summary per VST entry");
6168 Info->setSummary(std::move(AS));
6169 Combined = true;
6170 break;
6171 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006172 // FS_COMBINED_GLOBALVAR_INIT_REFS: [modid, linkage, n x valueid]
6173 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6174 uint64_t ModuleId = Record[0];
6175 uint64_t RawLinkage = Record[1];
6176 std::unique_ptr<GlobalVarSummary> FS =
6177 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
6178 FS->setModulePath(ModuleIdMap[ModuleId]);
6179 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6180 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006181 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006182 FS->addRefEdge(RefGUID);
6183 }
6184 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
6185 assert(!Info->summary() && "Expected a single summary per VST entry");
6186 Info->setSummary(std::move(FS));
6187 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006188 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006189 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006190 }
6191 }
6192 llvm_unreachable("Exit infinite loop");
6193}
6194
6195// Parse the module string table block into the Index.
6196// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006197std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006198 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6199 return error("Invalid record");
6200
6201 SmallVector<uint64_t, 64> Record;
6202
6203 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006204 ModulePathStringTableTy::iterator LastSeenModulePath;
Teresa Johnson403a7872015-10-04 14:33:43 +00006205 while (1) {
6206 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6207
6208 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006209 case BitstreamEntry::SubBlock: // Handled for us already.
6210 case BitstreamEntry::Error:
6211 return error("Malformed block");
6212 case BitstreamEntry::EndBlock:
6213 return std::error_code();
6214 case BitstreamEntry::Record:
6215 // The interesting case.
6216 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006217 }
6218
6219 Record.clear();
6220 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006221 default: // Default behavior: ignore.
6222 break;
6223 case bitc::MST_CODE_ENTRY: {
6224 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006225 uint64_t ModuleId = Record[0];
6226
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006227 if (convertToString(Record, 1, ModulePath))
6228 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006229
6230 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6231 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6232
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006233 ModulePath.clear();
6234 break;
6235 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006236 /// MST_CODE_HASH: [5*i32]
6237 case bitc::MST_CODE_HASH: {
6238 if (Record.size() != 5)
6239 return error("Invalid hash length " + Twine(Record.size()).str());
6240 if (LastSeenModulePath == TheIndex->modulePaths().end())
6241 return error("Invalid hash that does not follow a module path");
6242 int Pos = 0;
6243 for (auto &Val : Record) {
6244 assert(!(Val >> 32) && "Unexpected high bits set");
6245 LastSeenModulePath->second.second[Pos++] = Val;
6246 }
6247 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6248 LastSeenModulePath = TheIndex->modulePaths().end();
6249 break;
6250 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006251 }
6252 }
6253 llvm_unreachable("Exit infinite loop");
6254}
6255
6256// Parse the function info index from the bitcode streamer into the given index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006257std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6258 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006259 TheIndex = I;
6260
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006261 if (std::error_code EC = initStream(std::move(Streamer)))
6262 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006263
6264 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006265 if (!hasValidBitcodeHeader(Stream))
6266 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006267
6268 // We expect a number of well-defined blocks, though we don't necessarily
6269 // need to understand them all.
6270 while (1) {
6271 if (Stream.AtEndOfStream()) {
6272 // We didn't really read a proper Module block.
6273 return error("Malformed block");
6274 }
6275
6276 BitstreamEntry Entry =
6277 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6278
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006279 if (Entry.Kind != BitstreamEntry::SubBlock)
6280 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00006281
6282 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6283 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006284 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6285 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00006286
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006287 if (Stream.SkipBlock())
6288 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006289 }
6290}
6291
Teresa Johnson26ab5772016-03-15 00:04:37 +00006292// Parse the summary information at the given offset in the buffer into
6293// the index. Used to support lazy parsing of summaries from the
Teresa Johnson403a7872015-10-04 14:33:43 +00006294// combined index during importing.
6295// TODO: This function is not yet complete as it won't have a consumer
6296// until ThinLTO function importing is added.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006297std::error_code ModuleSummaryIndexBitcodeReader::parseGlobalValueSummary(
6298 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I,
6299 size_t SummaryOffset) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006300 TheIndex = I;
6301
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006302 if (std::error_code EC = initStream(std::move(Streamer)))
6303 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006304
6305 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006306 if (!hasValidBitcodeHeader(Stream))
6307 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006308
Teresa Johnson26ab5772016-03-15 00:04:37 +00006309 Stream.JumpToBit(SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +00006310
6311 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6312
6313 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006314 default:
6315 return error("Malformed block");
6316 case BitstreamEntry::Record:
6317 // The expected case.
6318 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006319 }
6320
6321 // TODO: Read a record. This interface will be completed when ThinLTO
6322 // importing is added so that it can be tested.
6323 SmallVector<uint64_t, 64> Record;
6324 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006325 case bitc::FS_COMBINED:
6326 case bitc::FS_COMBINED_PROFILE:
6327 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006328 default:
6329 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006330 }
6331
6332 return std::error_code();
6333}
6334
Teresa Johnson26ab5772016-03-15 00:04:37 +00006335std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6336 std::unique_ptr<DataStreamer> Streamer) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006337 if (Streamer)
6338 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00006339 return initStreamFromBuffer();
6340}
6341
Teresa Johnson26ab5772016-03-15 00:04:37 +00006342std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006343 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6344 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6345
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006346 if (Buffer->getBufferSize() & 3)
6347 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006348
6349 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6350 // The magic number is 0x0B17C0DE stored in little endian.
6351 if (isBitcodeWrapper(BufPtr, BufEnd))
6352 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6353 return error("Invalid bitcode wrapper header");
6354
6355 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6356 Stream.init(&*StreamFile);
6357
6358 return std::error_code();
6359}
6360
Teresa Johnson26ab5772016-03-15 00:04:37 +00006361std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
Teresa Johnson403a7872015-10-04 14:33:43 +00006362 std::unique_ptr<DataStreamer> Streamer) {
6363 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6364 // see it.
6365 auto OwnedBytes =
6366 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6367 StreamingMemoryObject &Bytes = *OwnedBytes;
6368 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6369 Stream.init(&*StreamFile);
6370
6371 unsigned char buf[16];
6372 if (Bytes.readBytes(buf, 16, 0) != 16)
6373 return error("Invalid bitcode signature");
6374
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006375 if (!isBitcode(buf, buf + 16))
6376 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006377
6378 if (isBitcodeWrapper(buf, buf + 4)) {
6379 const unsigned char *bitcodeStart = buf;
6380 const unsigned char *bitcodeEnd = buf + 16;
6381 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6382 Bytes.dropLeadingBytes(bitcodeStart - buf);
6383 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6384 }
6385 return std::error_code();
6386}
6387
Rafael Espindola48da4f42013-11-04 16:16:24 +00006388namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00006389class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00006390 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006391 return "llvm.bitcode";
6392 }
Craig Topper73156022014-03-02 09:09:27 +00006393 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006394 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006395 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006396 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006397 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006398 case BitcodeError::CorruptedBitcode:
6399 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006400 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006401 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006402 }
6403};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006404} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006405
Chris Bieneman770163e2014-09-19 20:29:02 +00006406static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6407
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006408const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006409 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006410}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006411
Chris Lattner6694f602007-04-29 07:54:31 +00006412//===----------------------------------------------------------------------===//
6413// External interface
6414//===----------------------------------------------------------------------===//
6415
Rafael Espindola456baad2015-06-17 01:15:47 +00006416static ErrorOr<std::unique_ptr<Module>>
6417getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6418 BitcodeReader *R, LLVMContext &Context,
6419 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6420 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6421 M->setMaterializer(R);
6422
6423 auto cleanupOnError = [&](std::error_code EC) {
6424 R->releaseBuffer(); // Never take ownership on error.
6425 return EC;
6426 };
6427
6428 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6429 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6430 ShouldLazyLoadMetadata))
6431 return cleanupOnError(EC);
6432
6433 if (MaterializeAll) {
6434 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00006435 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00006436 return cleanupOnError(EC);
6437 } else {
6438 // Resolve forward references from blockaddresses.
6439 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6440 return cleanupOnError(EC);
6441 }
6442 return std::move(M);
6443}
6444
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006445/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006446///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006447/// This isn't always used in a lazy context. In particular, it's also used by
6448/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6449/// in forward-referenced functions from block address references.
6450///
Rafael Espindola728074b2015-06-17 00:40:56 +00006451/// \param[in] MaterializeAll Set to \c true if we should materialize
6452/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006453static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00006454getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00006455 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006456 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006457 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006458
Rafael Espindola456baad2015-06-17 01:15:47 +00006459 ErrorOr<std::unique_ptr<Module>> Ret =
6460 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6461 MaterializeAll, ShouldLazyLoadMetadata);
6462 if (!Ret)
6463 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00006464
Rafael Espindolae2c1d772014-08-26 22:00:09 +00006465 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00006466 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00006467}
6468
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006469ErrorOr<std::unique_ptr<Module>>
6470llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6471 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006472 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006473 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006474}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006475
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006476ErrorOr<std::unique_ptr<Module>>
6477llvm::getStreamedBitcodeModule(StringRef Name,
6478 std::unique_ptr<DataStreamer> Streamer,
6479 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00006480 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006481 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00006482
6483 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6484 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006485}
6486
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006487ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6488 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006489 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006490 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006491 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6492 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006493}
Bill Wendling0198ce02010-10-06 01:22:42 +00006494
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006495std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6496 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006497 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006498 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00006499 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006500 if (Triple.getError())
6501 return "";
6502 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006503}
Teresa Johnson403a7872015-10-04 14:33:43 +00006504
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006505std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6506 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006507 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006508 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006509 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6510 if (ProducerString.getError())
6511 return "";
6512 return ProducerString.get();
6513}
6514
Teresa Johnson403a7872015-10-04 14:33:43 +00006515// Parse the specified bitcode buffer, returning the function info index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006516ErrorOr<std::unique_ptr<ModuleSummaryIndex>>
6517llvm::getModuleSummaryIndex(MemoryBufferRef Buffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006518 DiagnosticHandlerFunction DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006519 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006520 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006521
Teresa Johnson26ab5772016-03-15 00:04:37 +00006522 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006523
6524 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006525 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006526 return EC;
6527 };
6528
6529 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6530 return cleanupOnError(EC);
6531
Teresa Johnson26ab5772016-03-15 00:04:37 +00006532 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006533 return std::move(Index);
6534}
6535
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006536// Check if the given bitcode buffer contains a global value summary block.
6537bool llvm::hasGlobalValueSummary(MemoryBufferRef Buffer,
6538 DiagnosticHandlerFunction DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006539 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006540 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006541
6542 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006543 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006544 return false;
6545 };
6546
6547 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6548 return cleanupOnError(EC);
6549
Teresa Johnson26ab5772016-03-15 00:04:37 +00006550 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006551 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006552}