blob: e5c48120950605530b77a008eed17975f3353977 [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
Eugene Zelenko1804a772016-08-25 00:45:04 +000010#include "llvm/ADT/APFloat.h"
11#include "llvm/ADT/APInt.h"
12#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/None.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000015#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/SmallVector.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000018#include "llvm/ADT/StringRef.h"
David Majnemer3087b222015-01-20 05:58:07 +000019#include "llvm/ADT/Triple.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000020#include "llvm/ADT/Twine.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000021#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000022#include "llvm/Bitcode/LLVMBitCodes.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000023#include "llvm/Bitcode/ReaderWriter.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/IR/Argument.h"
25#include "llvm/IR/Attributes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000026#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000027#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CallingConv.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000029#include "llvm/IR/CallSite.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Comdat.h"
31#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Constants.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000033#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000034#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000035#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/DiagnosticInfo.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000038#include "llvm/IR/DiagnosticPrinter.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000039#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalAlias.h"
41#include "llvm/IR/GlobalIFunc.h"
42#include "llvm/IR/GlobalIndirectSymbol.h"
43#include "llvm/IR/GlobalObject.h"
44#include "llvm/IR/GlobalValue.h"
45#include "llvm/IR/GlobalVariable.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000046#include "llvm/IR/GVMaterializer.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/InlineAsm.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000048#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
50#include "llvm/IR/Instructions.h"
51#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000052#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000054#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/OperandTraits.h"
56#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000057#include "llvm/IR/TrackingMDRef.h"
58#include "llvm/IR/Type.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000059#include "llvm/IR/ValueHandle.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000060#include "llvm/Support/AtomicOrdering.h"
61#include "llvm/Support/Casting.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000062#include "llvm/Support/CommandLine.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000063#include "llvm/Support/Compiler.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000064#include "llvm/Support/Debug.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000065#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/ErrorOr.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000067#include "llvm/Support/ManagedStatic.h"
Chris Lattner6694f602007-04-29 07:54:31 +000068#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000069#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000070#include <algorithm>
71#include <cassert>
72#include <cstddef>
73#include <cstdint>
Benjamin Kramercced8be2015-03-17 20:40:24 +000074#include <deque>
Eugene Zelenko1804a772016-08-25 00:45:04 +000075#include <limits>
76#include <map>
77#include <memory>
78#include <string>
79#include <system_error>
80#include <tuple>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000081#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000082#include <vector>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000083
Chris Lattner1314b992007-04-22 06:23:29 +000084using namespace llvm;
85
Teresa Johnson916495d2016-04-04 18:52:58 +000086static cl::opt<bool> PrintSummaryGUIDs(
87 "print-summary-global-ids", cl::init(false), cl::Hidden,
88 cl::desc(
89 "Print the global id for each value when reading the module summary"));
90
Benjamin Kramercced8be2015-03-17 20:40:24 +000091namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +000092
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000093enum {
94 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
95};
96
Benjamin Kramercced8be2015-03-17 20:40:24 +000097class BitcodeReaderValueList {
98 std::vector<WeakVH> ValuePtrs;
99
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000100 /// As we resolve forward-referenced constants, we add information about them
101 /// to this vector. This allows us to resolve them in bulk instead of
102 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +0000103 /// ResolveConstantForwardRefs for more information about this.
104 ///
105 /// The key of this vector is the placeholder constant, the value is the slot
106 /// number that holds the resolved value.
107 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
108 ResolveConstantsTy ResolveConstants;
109 LLVMContext &Context;
Eugene Zelenko1804a772016-08-25 00:45:04 +0000110
Benjamin Kramercced8be2015-03-17 20:40:24 +0000111public:
112 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
113 ~BitcodeReaderValueList() {
114 assert(ResolveConstants.empty() && "Constants not resolved?");
115 }
116
117 // vector compatibility methods
118 unsigned size() const { return ValuePtrs.size(); }
119 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000120 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000121
122 void clear() {
123 assert(ResolveConstants.empty() && "Constants not resolved?");
124 ValuePtrs.clear();
125 }
126
127 Value *operator[](unsigned i) const {
128 assert(i < ValuePtrs.size());
129 return ValuePtrs[i];
130 }
131
132 Value *back() const { return ValuePtrs.back(); }
Duncan P. N. Exon Smith7457ecb2016-03-30 04:21:52 +0000133 void pop_back() { ValuePtrs.pop_back(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000134 bool empty() const { return ValuePtrs.empty(); }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000135
Benjamin Kramercced8be2015-03-17 20:40:24 +0000136 void shrinkTo(unsigned N) {
137 assert(N <= size() && "Invalid shrinkTo request!");
138 ValuePtrs.resize(N);
139 }
140
141 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000142 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000143
David Majnemer8a1c45d2015-12-12 05:38:55 +0000144 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000145
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000146 /// Once all constants are read, this method bulk resolves any forward
147 /// references.
148 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000149};
150
Teresa Johnson61b406e2015-12-29 23:00:22 +0000151class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000152 unsigned NumFwdRefs;
153 bool AnyFwdRefs;
154 unsigned MinFwdRef;
155 unsigned MaxFwdRef;
Duncan P. N. Exon Smith3c406c22016-04-20 20:14:09 +0000156
157 /// Array of metadata references.
158 ///
159 /// Don't use std::vector here. Some versions of libc++ copy (instead of
160 /// move) on resize, and TrackingMDRef is very expensive to copy.
161 SmallVector<TrackingMDRef, 1> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000162
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000163 /// Structures for resolving old type refs.
164 struct {
165 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
166 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
167 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
Duncan P. N. Exon Smith69bdc8a2016-04-23 21:36:59 +0000168 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000169 } OldTypeRefs;
170
Benjamin Kramercced8be2015-03-17 20:40:24 +0000171 LLVMContext &Context;
Eugene Zelenko1804a772016-08-25 00:45:04 +0000172
Benjamin Kramercced8be2015-03-17 20:40:24 +0000173public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000174 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000175 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000176
177 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000178 unsigned size() const { return MetadataPtrs.size(); }
179 void resize(unsigned N) { MetadataPtrs.resize(N); }
180 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
181 void clear() { MetadataPtrs.clear(); }
182 Metadata *back() const { return MetadataPtrs.back(); }
183 void pop_back() { MetadataPtrs.pop_back(); }
184 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000185
186 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000187 assert(i < MetadataPtrs.size());
188 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000189 }
190
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000191 Metadata *lookup(unsigned I) const {
Duncan P. N. Exon Smithe9f85c42016-04-23 04:23:57 +0000192 if (I < MetadataPtrs.size())
193 return MetadataPtrs[I];
194 return nullptr;
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000195 }
196
Benjamin Kramercced8be2015-03-17 20:40:24 +0000197 void shrinkTo(unsigned N) {
198 assert(N <= size() && "Invalid shrinkTo request!");
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000199 assert(!AnyFwdRefs && "Unexpected forward refs");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000200 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000201 }
202
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000203 /// Return the given metadata, creating a replaceable forward reference if
204 /// necessary.
Justin Bognerae341c62016-03-17 20:12:06 +0000205 Metadata *getMetadataFwdRef(unsigned Idx);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000206
207 /// Return the the given metadata only if it is fully resolved.
208 ///
209 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
210 /// would give \c false.
211 Metadata *getMetadataIfResolved(unsigned Idx);
212
Justin Bognerae341c62016-03-17 20:12:06 +0000213 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000214 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000215 void tryToResolveCycles();
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000216 bool hasFwdRefs() const { return AnyFwdRefs; }
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000217
218 /// Upgrade a type that had an MDString reference.
219 void addTypeRef(MDString &UUID, DICompositeType &CT);
220
221 /// Upgrade a type that had an MDString reference.
222 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
223
224 /// Upgrade a type ref array that may have MDString references.
225 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
226
227private:
228 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000229};
230
Peter Collingbourne6e860752016-09-23 18:27:42 +0000231class BitcodeReaderBase {
232protected:
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000233 BitcodeReaderBase(MemoryBufferRef Buffer) : Buffer(Buffer) {}
Peter Collingbourne6e860752016-09-23 18:27:42 +0000234
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000235 MemoryBufferRef Buffer;
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000236 BitstreamBlockInfo BlockInfo;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000237 BitstreamCursor Stream;
Peter Collingbourne6e860752016-09-23 18:27:42 +0000238
Peter Collingbourne028eb5a2016-11-02 00:08:19 +0000239 std::error_code initStream();
Peter Collingbourne939c7d92016-11-08 04:16:57 +0000240 bool readBlockInfo();
Peter Collingbourne6e860752016-09-23 18:27:42 +0000241
242 virtual std::error_code error(const Twine &Message) = 0;
243 virtual ~BitcodeReaderBase() = default;
244};
245
Peter Collingbourne028eb5a2016-11-02 00:08:19 +0000246std::error_code BitcodeReaderBase::initStream() {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000247 const unsigned char *BufPtr = (const unsigned char*)Buffer.getBufferStart();
248 const unsigned char *BufEnd = BufPtr+Buffer.getBufferSize();
Peter Collingbourne6e860752016-09-23 18:27:42 +0000249
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000250 if (Buffer.getBufferSize() & 3)
Peter Collingbourne6e860752016-09-23 18:27:42 +0000251 return error("Invalid bitcode signature");
252
253 // If we have a wrapper header, parse it and ignore the non-bc file contents.
254 // The magic number is 0x0B17C0DE stored in little endian.
255 if (isBitcodeWrapper(BufPtr, BufEnd))
256 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
257 return error("Invalid bitcode wrapper header");
258
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000259 Stream = BitstreamCursor(ArrayRef<uint8_t>(BufPtr, BufEnd));
260 Stream.setBlockInfo(&BlockInfo);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000261
262 return std::error_code();
263}
264
Peter Collingbourne6e860752016-09-23 18:27:42 +0000265class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
266 LLVMContext &Context;
267 Module *TheModule = nullptr;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000268 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000269 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000270 // Last function offset found in the VST.
271 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000272 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000273 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000274 // Contains an arbitrary and optional string identifying the bitcode producer
275 std::string ProducerIdentification;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000276
277 std::vector<Type*> TypeList;
278 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000279 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000280 std::vector<Comdat *> ComdatList;
281 SmallVector<Instruction *, 64> InstructionList;
282
283 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000284 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000285 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
286 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000287 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000288
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +0000289 bool HasSeenOldLoopTags = false;
290
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000291 /// The set of attributes by index. Index zero in the file is for null, and
292 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000293 std::vector<AttributeSet> MAttributes;
294
Karl Schimpf36440082015-08-31 16:43:55 +0000295 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000296 std::map<unsigned, AttributeSet> MAttributeGroups;
297
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000298 /// While parsing a function body, this is a list of the basic blocks for the
299 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000300 std::vector<BasicBlock*> FunctionBBs;
301
302 // When reading the module header, this list is populated with functions that
303 // have bodies later in the file.
304 std::vector<Function*> FunctionsWithBodies;
305
306 // When intrinsic functions are encountered which require upgrading they are
307 // stored here with their replacement function.
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000308 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
309 UpdatedIntrinsicMap UpgradedIntrinsics;
310 // Intrinsics which were remangled because of types rename
311 UpdatedIntrinsicMap RemangledIntrinsics;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000312
313 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
314 DenseMap<unsigned, unsigned> MDKindMap;
315
316 // Several operations happen after the module header has been read, but
317 // before function bodies are processed. This keeps track of whether
318 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000319 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000320
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000321 /// When function bodies are initially scanned, this map contains info about
322 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000323 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
324
325 /// When Metadata block is initially scanned when parsing the module, we may
326 /// choose to defer parsing of the metadata. This vector contains info about
327 /// which Metadata blocks are deferred.
328 std::vector<uint64_t> DeferredMetadataInfo;
329
330 /// These are basic blocks forward-referenced by block addresses. They are
331 /// inserted lazily into functions when they're loaded. The basic block ID is
332 /// its index into the vector.
333 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
334 std::deque<Function *> BasicBlockFwdRefQueue;
335
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000336 /// Indicates that we are using a new encoding for instruction operands where
337 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
338 /// instruction number, for a more compact encoding. Some instruction
339 /// operands are not relative to the instruction ID: basic block numbers, and
340 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000341 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000342 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000343
344 /// True if all functions will be materialized, negating the need to process
345 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000346 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000347
Benjamin Kramercced8be2015-03-17 20:40:24 +0000348 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000349 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000350
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000351 bool StripDebugInfo = false;
352
Peter Collingbourned4bff302015-11-05 22:03:56 +0000353 /// Functions that need to be matched with subprograms when upgrading old
354 /// metadata.
355 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
356
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000357 std::vector<std::string> BundleTags;
358
Benjamin Kramercced8be2015-03-17 20:40:24 +0000359public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000360 std::error_code error(BitcodeError E, const Twine &Message);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000361 std::error_code error(const Twine &Message) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000362
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000363 BitcodeReader(MemoryBufferRef Buffer, LLVMContext &Context);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000364
365 std::error_code materializeForwardReferencedFunctions();
366
Benjamin Kramercced8be2015-03-17 20:40:24 +0000367 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000368 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000369 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000370
Rafael Espindola6ace6852015-06-15 21:02:49 +0000371 /// \brief Main interface to parsing a bitcode buffer.
372 /// \returns true if an error occurred.
Peter Collingbourne028eb5a2016-11-02 00:08:19 +0000373 std::error_code parseBitcodeInto(Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000374 bool ShouldLazyLoadMetadata = false);
375
Rafael Espindola6ace6852015-06-15 21:02:49 +0000376 /// \brief Cheap mechanism to just extract module triple
377 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000378 ErrorOr<std::string> parseTriple();
379
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000380 /// Cheap mechanism to just extract the identification block out of bitcode.
381 ErrorOr<std::string> parseIdentificationBlock();
382
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000383 /// Peak at the module content and return true if any ObjC category or class
384 /// is found.
385 ErrorOr<bool> hasObjCCategory();
386
Benjamin Kramercced8be2015-03-17 20:40:24 +0000387 static uint64_t decodeSignRotatedValue(uint64_t V);
388
389 /// Materialize any deferred Metadata block.
390 std::error_code materializeMetadata() override;
391
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000392 void setStripDebugInfo() override;
393
Benjamin Kramercced8be2015-03-17 20:40:24 +0000394private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000395 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
396 // ProducerIdentification data member, and do some basic enforcement on the
397 // "epoch" encoded in the bitcode.
398 std::error_code parseBitcodeVersion();
399
Benjamin Kramercced8be2015-03-17 20:40:24 +0000400 std::vector<StructType *> IdentifiedStructTypes;
401 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
402 StructType *createIdentifiedStructType(LLVMContext &Context);
403
404 Type *getTypeByID(unsigned ID);
Eugene Zelenko1804a772016-08-25 00:45:04 +0000405
David Majnemer8a1c45d2015-12-12 05:38:55 +0000406 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000407 if (Ty && Ty->isMetadataTy())
408 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000409 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000410 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000411
Benjamin Kramercced8be2015-03-17 20:40:24 +0000412 Metadata *getFnMetadataByID(unsigned ID) {
Justin Bognerae341c62016-03-17 20:12:06 +0000413 return MetadataList.getMetadataFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000414 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000415
Benjamin Kramercced8be2015-03-17 20:40:24 +0000416 BasicBlock *getBasicBlock(unsigned ID) const {
417 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
418 return FunctionBBs[ID];
419 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000420
Benjamin Kramercced8be2015-03-17 20:40:24 +0000421 AttributeSet getAttributes(unsigned i) const {
422 if (i-1 < MAttributes.size())
423 return MAttributes[i-1];
424 return AttributeSet();
425 }
426
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000427 /// Read a value/type pair out of the specified record from slot 'Slot'.
428 /// Increment Slot past the number of slots used in the record. Return true on
429 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000430 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
431 unsigned InstNum, Value *&ResVal) {
432 if (Slot == Record.size()) return true;
433 unsigned ValNo = (unsigned)Record[Slot++];
434 // Adjust the ValNo, if it was encoded relative to the InstNum.
435 if (UseRelativeIDs)
436 ValNo = InstNum - ValNo;
437 if (ValNo < InstNum) {
438 // If this is not a forward reference, just return the value we already
439 // have.
440 ResVal = getFnValueByID(ValNo, nullptr);
441 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000442 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000443 if (Slot == Record.size())
444 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000445
446 unsigned TypeNo = (unsigned)Record[Slot++];
447 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
448 return ResVal == nullptr;
449 }
450
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000451 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
452 /// past the number of slots used by the value in the record. Return true if
453 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000454 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000455 unsigned InstNum, Type *Ty, Value *&ResVal) {
456 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000457 return true;
458 // All values currently take a single record slot.
459 ++Slot;
460 return false;
461 }
462
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000463 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000464 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000465 unsigned InstNum, Type *Ty, Value *&ResVal) {
466 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000467 return ResVal == nullptr;
468 }
469
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000470 /// Version of getValue that returns ResVal directly, or 0 if there is an
471 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000472 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000473 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000474 if (Slot == Record.size()) return nullptr;
475 unsigned ValNo = (unsigned)Record[Slot];
476 // Adjust the ValNo, if it was encoded relative to the InstNum.
477 if (UseRelativeIDs)
478 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000479 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000480 }
481
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000482 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000483 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000484 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000485 if (Slot == Record.size()) return nullptr;
486 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
487 // Adjust the ValNo, if it was encoded relative to the InstNum.
488 if (UseRelativeIDs)
489 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000490 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000491 }
492
493 /// Converts alignment exponent (i.e. power of two (or zero)) to the
494 /// corresponding alignment to use. If alignment is too large, returns
495 /// a corresponding error code.
496 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000497 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000498 std::error_code parseModule(uint64_t ResumeBit,
499 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000500 std::error_code parseAttributeBlock();
501 std::error_code parseAttributeGroupBlock();
502 std::error_code parseTypeTable();
503 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000504 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000505
Teresa Johnsonff642b92015-09-17 20:12:00 +0000506 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
507 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000508 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000509 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000510 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000511 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000512 /// Save the positions of the Metadata blocks and skip parsing the blocks.
513 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000514 std::error_code parseFunctionBody(Function *F);
515 std::error_code globalCleanup();
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000516 std::error_code resolveGlobalAndIndirectSymbolInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000517 std::error_code parseMetadata(bool ModuleLevel = false);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000518 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
519 StringRef Blob,
520 unsigned &NextMetadataNo);
Teresa Johnson12545072015-11-15 02:00:09 +0000521 std::error_code parseMetadataKinds();
522 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000523 std::error_code
524 parseGlobalObjectAttachment(GlobalObject &GO,
525 ArrayRef<uint64_t> Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000526 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000527 ErrorOr<std::string> parseModuleTriple();
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000528 ErrorOr<bool> hasObjCCategoryInModule();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000529 std::error_code parseUseLists();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000530 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000531 Function *F,
532 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
533};
Teresa Johnson403a7872015-10-04 14:33:43 +0000534
535/// Class to manage reading and parsing function summary index bitcode
536/// files/sections.
Peter Collingbourne6e860752016-09-23 18:27:42 +0000537class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
Teresa Johnson403a7872015-10-04 14:33:43 +0000538 DiagnosticHandlerFunction DiagnosticHandler;
539
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000540 /// Eventually points to the module index built during parsing.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000541 ModuleSummaryIndex *TheIndex = nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000542
Teresa Johnson403a7872015-10-04 14:33:43 +0000543 /// Used to indicate whether caller only wants to check for the presence
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000544 /// of the global value summary bitcode section. All blocks are skipped,
545 /// but the SeenGlobalValSummary boolean is set.
546 bool CheckGlobalValSummaryPresenceOnly = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000547
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000548 /// Indicates whether we have encountered a global value summary section
549 /// yet during parsing, used when checking if file contains global value
Teresa Johnson403a7872015-10-04 14:33:43 +0000550 /// summary section.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000551 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000552
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000553 /// Indicates whether we have already parsed the VST, used for error checking.
554 bool SeenValueSymbolTable = false;
555
556 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
557 /// Used to enable on-demand parsing of the VST.
558 uint64_t VSTOffset = 0;
559
560 // Map to save ValueId to GUID association that was recorded in the
561 // ValueSymbolTable. It is used after the VST is parsed to convert
562 // call graph edges read from the function summary from referencing
563 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000564 // they are recorded in the summary index being built.
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000565 // We save a second GUID which is the same as the first one, but ignoring the
566 // linkage, i.e. for value other than local linkage they are identical.
567 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
568 ValueIdToCallGraphGUIDMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000569
Teresa Johnson403a7872015-10-04 14:33:43 +0000570 /// Map populated during module path string table parsing, from the
571 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000572 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000573 /// summary records.
574 DenseMap<uint64_t, StringRef> ModuleIdMap;
575
Teresa Johnsone1164de2016-02-10 21:55:02 +0000576 /// Original source file name recorded in a bitcode record.
577 std::string SourceFileName;
578
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000579public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000580 std::error_code error(const Twine &Message);
581
Teresa Johnson26ab5772016-03-15 00:04:37 +0000582 ModuleSummaryIndexBitcodeReader(
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000583 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000584 bool CheckGlobalValSummaryPresenceOnly = false);
Teresa Johnson403a7872015-10-04 14:33:43 +0000585
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000586 /// Check if the parser has encountered a summary section.
587 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
Teresa Johnson403a7872015-10-04 14:33:43 +0000588
589 /// \brief Main interface to parsing a bitcode buffer.
590 /// \returns true if an error occurred.
Peter Collingbourne028eb5a2016-11-02 00:08:19 +0000591 std::error_code parseSummaryIndexInto(ModuleSummaryIndex *I);
Teresa Johnson403a7872015-10-04 14:33:43 +0000592
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000593private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000594 std::error_code parseModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000595 std::error_code parseValueSymbolTable(
596 uint64_t Offset,
597 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Teresa Johnson403a7872015-10-04 14:33:43 +0000598 std::error_code parseEntireSummary();
599 std::error_code parseModuleStringTable();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000600 std::pair<GlobalValue::GUID, GlobalValue::GUID>
Eugene Zelenko1804a772016-08-25 00:45:04 +0000601
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000602 getGUIDFromValueId(unsigned ValueId);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000603 std::pair<GlobalValue::GUID, CalleeInfo::HotnessType>
604 readCallGraphEdge(const SmallVector<uint64_t, 64> &Record, unsigned int &I,
605 bool IsOldProfileFormat, bool HasProfile);
Teresa Johnson403a7872015-10-04 14:33:43 +0000606};
Eugene Zelenko1804a772016-08-25 00:45:04 +0000607
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000608} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000609
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000610BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
611 DiagnosticSeverity Severity,
612 const Twine &Msg)
613 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
614
615void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
616
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000617static std::error_code error(const DiagnosticHandlerFunction &DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000618 std::error_code EC, const Twine &Message) {
619 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
620 DiagnosticHandler(DI);
621 return EC;
622}
623
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000624static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000625 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000626 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
627 Message);
628}
629
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000630static std::error_code error(LLVMContext &Context, const Twine &Message) {
631 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
632 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000633}
634
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000635std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000636 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000637 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000638 Message + " (Producer: '" + ProducerIdentification +
639 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000640 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000641 return ::error(Context, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000642}
643
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000644std::error_code BitcodeReader::error(const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000645 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000646 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000647 Message + " (Producer: '" + ProducerIdentification +
648 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000649 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000650 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
651 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000652}
653
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000654BitcodeReader::BitcodeReader(MemoryBufferRef Buffer, LLVMContext &Context)
Peter Collingbourne6e860752016-09-23 18:27:42 +0000655 : BitcodeReaderBase(Buffer), Context(Context), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000656 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000657
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000658std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
659 if (WillMaterializeAllForwardRefs)
660 return std::error_code();
661
662 // Prevent recursion.
663 WillMaterializeAllForwardRefs = true;
664
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000665 while (!BasicBlockFwdRefQueue.empty()) {
666 Function *F = BasicBlockFwdRefQueue.front();
667 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000668 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000669 if (!BasicBlockFwdRefs.count(F))
670 // Already materialized.
671 continue;
672
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000673 // Check for a function that isn't materializable to prevent an infinite
674 // loop. When parsing a blockaddress stored in a global variable, there
675 // isn't a trivial way to check if a function will have a body without a
676 // linear search through FunctionsWithBodies, so just check it here.
677 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000678 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000679
680 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000681 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000682 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000683 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000684 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000685
686 // Reset state.
687 WillMaterializeAllForwardRefs = false;
688 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000689}
690
Chris Lattnerfee5a372007-05-04 03:30:17 +0000691//===----------------------------------------------------------------------===//
692// Helper functions to implement forward reference resolution, etc.
693//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000694
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000695/// Convert a string from a record into an std::string, return true on failure.
696template <typename StrTy>
697static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000698 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000699 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000700 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000701
Chris Lattnere14cb882007-05-04 19:11:41 +0000702 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
703 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000704 return false;
705}
706
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000707static bool hasImplicitComdat(size_t Val) {
708 switch (Val) {
709 default:
710 return false;
711 case 1: // Old WeakAnyLinkage
712 case 4: // Old LinkOnceAnyLinkage
713 case 10: // Old WeakODRLinkage
714 case 11: // Old LinkOnceODRLinkage
715 return true;
716 }
717}
718
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000719static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000720 switch (Val) {
721 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000722 case 0:
723 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000724 case 2:
725 return GlobalValue::AppendingLinkage;
726 case 3:
727 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000728 case 5:
729 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
730 case 6:
731 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
732 case 7:
733 return GlobalValue::ExternalWeakLinkage;
734 case 8:
735 return GlobalValue::CommonLinkage;
736 case 9:
737 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000738 case 12:
739 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000740 case 13:
741 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
742 case 14:
743 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000744 case 15:
745 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000746 case 1: // Old value with implicit comdat.
747 case 16:
748 return GlobalValue::WeakAnyLinkage;
749 case 10: // Old value with implicit comdat.
750 case 17:
751 return GlobalValue::WeakODRLinkage;
752 case 4: // Old value with implicit comdat.
753 case 18:
754 return GlobalValue::LinkOnceAnyLinkage;
755 case 11: // Old value with implicit comdat.
756 case 19:
757 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000758 }
759}
760
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000761/// Decode the flags for GlobalValue in the summary.
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000762static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
763 uint64_t Version) {
764 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
765 // like getDecodedLinkage() above. Any future change to the linkage enum and
766 // to getDecodedLinkage() will need to be taken into account here as above.
767 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000768 RawFlags = RawFlags >> 4;
Teresa Johnson58fbc912016-10-28 02:24:59 +0000769 bool NoRename = RawFlags & 0x1;
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000770 bool IsNotViableToInline = RawFlags & 0x2;
Teresa Johnson58fbc912016-10-28 02:24:59 +0000771 return GlobalValueSummary::GVFlags(Linkage, NoRename, IsNotViableToInline);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000772}
773
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000774static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000775 switch (Val) {
776 default: // Map unknown visibilities to default.
777 case 0: return GlobalValue::DefaultVisibility;
778 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000779 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000780 }
781}
782
Nico Rieck7157bb72014-01-14 15:22:47 +0000783static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000784getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000785 switch (Val) {
786 default: // Map unknown values to default.
787 case 0: return GlobalValue::DefaultStorageClass;
788 case 1: return GlobalValue::DLLImportStorageClass;
789 case 2: return GlobalValue::DLLExportStorageClass;
790 }
791}
792
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000793static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000794 switch (Val) {
795 case 0: return GlobalVariable::NotThreadLocal;
796 default: // Map unknown non-zero value to general dynamic.
797 case 1: return GlobalVariable::GeneralDynamicTLSModel;
798 case 2: return GlobalVariable::LocalDynamicTLSModel;
799 case 3: return GlobalVariable::InitialExecTLSModel;
800 case 4: return GlobalVariable::LocalExecTLSModel;
801 }
802}
803
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000804static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
805 switch (Val) {
806 default: // Map unknown to UnnamedAddr::None.
807 case 0: return GlobalVariable::UnnamedAddr::None;
808 case 1: return GlobalVariable::UnnamedAddr::Global;
809 case 2: return GlobalVariable::UnnamedAddr::Local;
810 }
811}
812
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000813static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000814 switch (Val) {
815 default: return -1;
816 case bitc::CAST_TRUNC : return Instruction::Trunc;
817 case bitc::CAST_ZEXT : return Instruction::ZExt;
818 case bitc::CAST_SEXT : return Instruction::SExt;
819 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
820 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
821 case bitc::CAST_UITOFP : return Instruction::UIToFP;
822 case bitc::CAST_SITOFP : return Instruction::SIToFP;
823 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
824 case bitc::CAST_FPEXT : return Instruction::FPExt;
825 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
826 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
827 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000828 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000829 }
830}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000831
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000832static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000833 bool IsFP = Ty->isFPOrFPVectorTy();
834 // BinOps are only valid for int/fp or vector of int/fp types
835 if (!IsFP && !Ty->isIntOrIntVectorTy())
836 return -1;
837
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000838 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000839 default:
840 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000841 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000842 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000843 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000844 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000845 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000846 return IsFP ? Instruction::FMul : Instruction::Mul;
847 case bitc::BINOP_UDIV:
848 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000849 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000850 return IsFP ? Instruction::FDiv : Instruction::SDiv;
851 case bitc::BINOP_UREM:
852 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000853 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000854 return IsFP ? Instruction::FRem : Instruction::SRem;
855 case bitc::BINOP_SHL:
856 return IsFP ? -1 : Instruction::Shl;
857 case bitc::BINOP_LSHR:
858 return IsFP ? -1 : Instruction::LShr;
859 case bitc::BINOP_ASHR:
860 return IsFP ? -1 : Instruction::AShr;
861 case bitc::BINOP_AND:
862 return IsFP ? -1 : Instruction::And;
863 case bitc::BINOP_OR:
864 return IsFP ? -1 : Instruction::Or;
865 case bitc::BINOP_XOR:
866 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000867 }
868}
869
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000870static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000871 switch (Val) {
872 default: return AtomicRMWInst::BAD_BINOP;
873 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
874 case bitc::RMW_ADD: return AtomicRMWInst::Add;
875 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
876 case bitc::RMW_AND: return AtomicRMWInst::And;
877 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
878 case bitc::RMW_OR: return AtomicRMWInst::Or;
879 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
880 case bitc::RMW_MAX: return AtomicRMWInst::Max;
881 case bitc::RMW_MIN: return AtomicRMWInst::Min;
882 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
883 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
884 }
885}
886
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000887static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000888 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +0000889 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
890 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
891 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
892 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
893 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
894 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000895 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +0000896 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000897 }
898}
899
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000900static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000901 switch (Val) {
902 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
903 default: // Map unknown scopes to cross-thread.
904 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
905 }
906}
907
David Majnemerdad0a642014-06-27 18:19:56 +0000908static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
909 switch (Val) {
910 default: // Map unknown selection kinds to any.
911 case bitc::COMDAT_SELECTION_KIND_ANY:
912 return Comdat::Any;
913 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
914 return Comdat::ExactMatch;
915 case bitc::COMDAT_SELECTION_KIND_LARGEST:
916 return Comdat::Largest;
917 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
918 return Comdat::NoDuplicates;
919 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
920 return Comdat::SameSize;
921 }
922}
923
James Molloy88eb5352015-07-10 12:52:00 +0000924static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
925 FastMathFlags FMF;
926 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
927 FMF.setUnsafeAlgebra();
928 if (0 != (Val & FastMathFlags::NoNaNs))
929 FMF.setNoNaNs();
930 if (0 != (Val & FastMathFlags::NoInfs))
931 FMF.setNoInfs();
932 if (0 != (Val & FastMathFlags::NoSignedZeros))
933 FMF.setNoSignedZeros();
934 if (0 != (Val & FastMathFlags::AllowReciprocal))
935 FMF.setAllowReciprocal();
936 return FMF;
937}
938
Eugene Zelenko1804a772016-08-25 00:45:04 +0000939static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000940 switch (Val) {
941 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
942 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
943 }
944}
945
Gabor Greiff6caff662008-05-10 08:32:32 +0000946namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000947namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000948
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000949/// \brief A class for maintaining the slot number definition
950/// as a placeholder for the actual definition for forward constants defs.
951class ConstantPlaceHolder : public ConstantExpr {
952 void operator=(const ConstantPlaceHolder &) = delete;
953
954public:
955 // allocate space for exactly one operand
956 void *operator new(size_t s) { return User::operator new(s, 1); }
957 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000958 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000959 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
960 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000961
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000962 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
963 static bool classof(const Value *V) {
964 return isa<ConstantExpr>(V) &&
965 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000967
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000968 /// Provide fast operand accessors
969 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
970};
Eugene Zelenko1804a772016-08-25 00:45:04 +0000971
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000972} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000973
Chris Lattner2d8cd802009-03-31 22:55:09 +0000974// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000975template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000976struct OperandTraits<ConstantPlaceHolder> :
977 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000978};
Richard Trieue3d126c2014-11-21 02:42:08 +0000979DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko1804a772016-08-25 00:45:04 +0000980
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000981} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000982
David Majnemer8a1c45d2015-12-12 05:38:55 +0000983void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000984 if (Idx == size()) {
985 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000986 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000988
Chris Lattner2d8cd802009-03-31 22:55:09 +0000989 if (Idx >= size())
990 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000991
Chris Lattner2d8cd802009-03-31 22:55:09 +0000992 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000993 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000994 OldV = V;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000995 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000996 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000997
Chris Lattner2d8cd802009-03-31 22:55:09 +0000998 // Handle constants and non-constants (e.g. instrs) differently for
999 // efficiency.
1000 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
1001 ResolveConstants.push_back(std::make_pair(PHC, Idx));
1002 OldV = V;
1003 } else {
1004 // If there was a forward reference to this value, replace it.
1005 Value *PrevVal = OldV;
1006 OldV->replaceAllUsesWith(V);
1007 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +00001008 }
1009}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001010
Chris Lattner1663cca2007-04-24 05:48:56 +00001011Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +00001012 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +00001013 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +00001014 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +00001015
Chris Lattner2d8cd802009-03-31 22:55:09 +00001016 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +00001017 if (Ty != V->getType())
1018 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +00001019 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001020 }
Chris Lattner1663cca2007-04-24 05:48:56 +00001021
1022 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +00001023 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001024 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +00001025 return C;
1026}
1027
David Majnemer8a1c45d2015-12-12 05:38:55 +00001028Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +00001029 // Bail out for a clearly invalid value. This would make us call resize(0)
Eugene Zelenko1804a772016-08-25 00:45:04 +00001030 if (Idx == std::numeric_limits<unsigned>::max())
Filipe Cabecinhasbad07792015-04-30 00:52:42 +00001031 return nullptr;
1032
Chris Lattner2d8cd802009-03-31 22:55:09 +00001033 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +00001034 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001035
Chris Lattner2d8cd802009-03-31 22:55:09 +00001036 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +00001037 // If the types don't match, it's invalid.
1038 if (Ty && Ty != V->getType())
1039 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +00001040 return V;
Chris Lattner83930552007-05-01 07:01:57 +00001041 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001042
Chris Lattner1fc27f02007-05-02 05:16:49 +00001043 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +00001044 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Chris Lattner83930552007-05-01 07:01:57 +00001046 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +00001047 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001048 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +00001049 return V;
1050}
1051
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001052/// Once all constants are read, this method bulk resolves any forward
1053/// references. The idea behind this is that we sometimes get constants (such
1054/// as large arrays) which reference *many* forward ref constants. Replacing
1055/// each of these causes a lot of thrashing when building/reuniquing the
1056/// constant. Instead of doing this, we look at all the uses and rewrite all
1057/// the place holders at once for any constant that uses a placeholder.
1058void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001059 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +00001060 // binary search.
1061 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001062
Chris Lattner74429932008-08-21 02:34:16 +00001063 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001064
Chris Lattner74429932008-08-21 02:34:16 +00001065 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +00001066 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +00001067 Constant *Placeholder = ResolveConstants.back().first;
1068 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001069
Chris Lattner74429932008-08-21 02:34:16 +00001070 // Loop over all users of the placeholder, updating them to reference the
1071 // new value. If they reference more than one placeholder, update them all
1072 // at once.
1073 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001074 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +00001075 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001076
Chris Lattner74429932008-08-21 02:34:16 +00001077 // If the using object isn't uniqued, just update the operands. This
1078 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001079 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +00001080 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001081 continue;
1082 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001083
Chris Lattner74429932008-08-21 02:34:16 +00001084 // Otherwise, we have a constant that uses the placeholder. Replace that
1085 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001086 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +00001087 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1088 I != E; ++I) {
1089 Value *NewOp;
1090 if (!isa<ConstantPlaceHolder>(*I)) {
1091 // Not a placeholder reference.
1092 NewOp = *I;
1093 } else if (*I == Placeholder) {
1094 // Common case is that it just references this one placeholder.
1095 NewOp = RealVal;
1096 } else {
1097 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001098 ResolveConstantsTy::iterator It =
1099 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001100 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1101 0));
1102 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001103 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001104 }
1105
1106 NewOps.push_back(cast<Constant>(NewOp));
1107 }
1108
1109 // Make the new constant.
1110 Constant *NewC;
1111 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001112 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001113 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001114 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001115 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001116 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001117 } else {
1118 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001119 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001120 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001121
Chris Lattner74429932008-08-21 02:34:16 +00001122 UserC->replaceAllUsesWith(NewC);
1123 UserC->destroyConstant();
1124 NewOps.clear();
1125 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001126
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001127 // Update all ValueHandles, they should be the only users at this point.
1128 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001129 delete Placeholder;
1130 }
1131}
1132
Teresa Johnson61b406e2015-12-29 23:00:22 +00001133void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001134 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001135 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001136 return;
1137 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001138
Devang Patel05eb6172009-08-04 06:00:18 +00001139 if (Idx >= size())
1140 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001141
Teresa Johnson61b406e2015-12-29 23:00:22 +00001142 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001143 if (!OldMD) {
1144 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001145 return;
1146 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001147
Devang Patel05eb6172009-08-04 06:00:18 +00001148 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001149 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001150 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001151 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001152}
1153
Justin Bognerae341c62016-03-17 20:12:06 +00001154Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001155 if (Idx >= size())
1156 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001157
Teresa Johnson61b406e2015-12-29 23:00:22 +00001158 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001159 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001160
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001161 // Track forward refs to be resolved later.
1162 if (AnyFwdRefs) {
1163 MinFwdRef = std::min(MinFwdRef, Idx);
1164 MaxFwdRef = std::max(MaxFwdRef, Idx);
1165 } else {
1166 AnyFwdRefs = true;
1167 MinFwdRef = MaxFwdRef = Idx;
1168 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001169 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001170
1171 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001172 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001173 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001174 return MD;
1175}
1176
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00001177Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
1178 Metadata *MD = lookup(Idx);
1179 if (auto *N = dyn_cast_or_null<MDNode>(MD))
1180 if (!N->isResolved())
1181 return nullptr;
1182 return MD;
1183}
1184
Justin Bognerae341c62016-03-17 20:12:06 +00001185MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1186 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1187}
1188
Teresa Johnson61b406e2015-12-29 23:00:22 +00001189void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001190 if (NumFwdRefs)
1191 // Still forward references... can't resolve cycles.
1192 return;
1193
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001194 bool DidReplaceTypeRefs = false;
1195
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001196 // Give up on finding a full definition for any forward decls that remain.
1197 for (const auto &Ref : OldTypeRefs.FwdDecls)
1198 OldTypeRefs.Final.insert(Ref);
1199 OldTypeRefs.FwdDecls.clear();
1200
1201 // Upgrade from old type ref arrays. In strange cases, this could add to
1202 // OldTypeRefs.Unknown.
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001203 for (const auto &Array : OldTypeRefs.Arrays) {
1204 DidReplaceTypeRefs = true;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001205 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001206 }
1207 OldTypeRefs.Arrays.clear();
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001208
1209 // Replace old string-based type refs with the resolved node, if possible.
1210 // If we haven't seen the node, leave it to the verifier to complain about
1211 // the invalid string reference.
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001212 for (const auto &Ref : OldTypeRefs.Unknown) {
1213 DidReplaceTypeRefs = true;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001214 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
1215 Ref.second->replaceAllUsesWith(CT);
1216 else
1217 Ref.second->replaceAllUsesWith(Ref.first);
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001218 }
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001219 OldTypeRefs.Unknown.clear();
1220
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001221 // Make sure all the upgraded types are resolved.
1222 if (DidReplaceTypeRefs) {
1223 AnyFwdRefs = true;
1224 MinFwdRef = 0;
1225 MaxFwdRef = MetadataPtrs.size() - 1;
1226 }
1227
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001228 if (!AnyFwdRefs)
1229 // Nothing to do.
1230 return;
1231
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001232 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001233 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001234 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001235 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001236 if (!N)
1237 continue;
1238
1239 assert(!N->isTemporary() && "Unexpected forward reference");
1240 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001241 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001242
1243 // Make sure we return early again until there's another forward ref.
1244 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001245}
Chris Lattner1314b992007-04-22 06:23:29 +00001246
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001247void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
1248 DICompositeType &CT) {
1249 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
1250 if (CT.isForwardDecl())
1251 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
1252 else
1253 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
1254}
1255
1256Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
1257 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
1258 if (LLVM_LIKELY(!UUID))
1259 return MaybeUUID;
1260
1261 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
1262 return CT;
1263
1264 auto &Ref = OldTypeRefs.Unknown[UUID];
1265 if (!Ref)
1266 Ref = MDNode::getTemporary(Context, None);
1267 return Ref.get();
1268}
1269
1270Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
1271 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1272 if (!Tuple || Tuple->isDistinct())
1273 return MaybeTuple;
1274
1275 // Look through the array immediately if possible.
1276 if (!Tuple->isTemporary())
1277 return resolveTypeRefArray(Tuple);
1278
1279 // Create and return a placeholder to use for now. Eventually
1280 // resolveTypeRefArrays() will be resolve this forward reference.
Duncan P. N. Exon Smithc3f89972016-06-09 20:46:33 +00001281 OldTypeRefs.Arrays.emplace_back(
1282 std::piecewise_construct, std::forward_as_tuple(Tuple),
1283 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001284 return OldTypeRefs.Arrays.back().second.get();
1285}
1286
1287Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
1288 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1289 if (!Tuple || Tuple->isDistinct())
1290 return MaybeTuple;
1291
1292 // Look through the DITypeRefArray, upgrading each DITypeRef.
1293 SmallVector<Metadata *, 32> Ops;
1294 Ops.reserve(Tuple->getNumOperands());
1295 for (Metadata *MD : Tuple->operands())
1296 Ops.push_back(upgradeTypeRef(MD));
1297
1298 return MDTuple::get(Context, Ops);
1299}
1300
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001301Type *BitcodeReader::getTypeByID(unsigned ID) {
1302 // The type table size is always specified correctly.
1303 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001304 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001305
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001306 if (Type *Ty = TypeList[ID])
1307 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001308
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001309 // If we have a forward reference, the only possible case is when it is to a
1310 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001311 return TypeList[ID] = createIdentifiedStructType(Context);
1312}
1313
1314StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1315 StringRef Name) {
1316 auto *Ret = StructType::create(Context, Name);
1317 IdentifiedStructTypes.push_back(Ret);
1318 return Ret;
1319}
1320
1321StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1322 auto *Ret = StructType::create(Context);
1323 IdentifiedStructTypes.push_back(Ret);
1324 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001325}
1326
Chris Lattnerfee5a372007-05-04 03:30:17 +00001327//===----------------------------------------------------------------------===//
1328// Functions for parsing blocks from the bitcode file
1329//===----------------------------------------------------------------------===//
1330
Amaury Sechet74084c42016-11-06 07:48:46 +00001331static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1332 switch (Val) {
1333 case Attribute::EndAttrKinds:
1334 llvm_unreachable("Synthetic enumerators which should never get here");
1335
1336 case Attribute::None: return 0;
1337 case Attribute::ZExt: return 1 << 0;
1338 case Attribute::SExt: return 1 << 1;
1339 case Attribute::NoReturn: return 1 << 2;
1340 case Attribute::InReg: return 1 << 3;
1341 case Attribute::StructRet: return 1 << 4;
1342 case Attribute::NoUnwind: return 1 << 5;
1343 case Attribute::NoAlias: return 1 << 6;
1344 case Attribute::ByVal: return 1 << 7;
1345 case Attribute::Nest: return 1 << 8;
1346 case Attribute::ReadNone: return 1 << 9;
1347 case Attribute::ReadOnly: return 1 << 10;
1348 case Attribute::NoInline: return 1 << 11;
1349 case Attribute::AlwaysInline: return 1 << 12;
1350 case Attribute::OptimizeForSize: return 1 << 13;
1351 case Attribute::StackProtect: return 1 << 14;
1352 case Attribute::StackProtectReq: return 1 << 15;
1353 case Attribute::Alignment: return 31 << 16;
1354 case Attribute::NoCapture: return 1 << 21;
1355 case Attribute::NoRedZone: return 1 << 22;
1356 case Attribute::NoImplicitFloat: return 1 << 23;
1357 case Attribute::Naked: return 1 << 24;
1358 case Attribute::InlineHint: return 1 << 25;
1359 case Attribute::StackAlignment: return 7 << 26;
1360 case Attribute::ReturnsTwice: return 1 << 29;
1361 case Attribute::UWTable: return 1 << 30;
1362 case Attribute::NonLazyBind: return 1U << 31;
1363 case Attribute::SanitizeAddress: return 1ULL << 32;
1364 case Attribute::MinSize: return 1ULL << 33;
1365 case Attribute::NoDuplicate: return 1ULL << 34;
1366 case Attribute::StackProtectStrong: return 1ULL << 35;
1367 case Attribute::SanitizeThread: return 1ULL << 36;
1368 case Attribute::SanitizeMemory: return 1ULL << 37;
1369 case Attribute::NoBuiltin: return 1ULL << 38;
1370 case Attribute::Returned: return 1ULL << 39;
1371 case Attribute::Cold: return 1ULL << 40;
1372 case Attribute::Builtin: return 1ULL << 41;
1373 case Attribute::OptimizeNone: return 1ULL << 42;
1374 case Attribute::InAlloca: return 1ULL << 43;
1375 case Attribute::NonNull: return 1ULL << 44;
1376 case Attribute::JumpTable: return 1ULL << 45;
1377 case Attribute::Convergent: return 1ULL << 46;
1378 case Attribute::SafeStack: return 1ULL << 47;
1379 case Attribute::NoRecurse: return 1ULL << 48;
1380 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1381 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1382 case Attribute::SwiftSelf: return 1ULL << 51;
1383 case Attribute::SwiftError: return 1ULL << 52;
1384 case Attribute::WriteOnly: return 1ULL << 53;
1385 case Attribute::Dereferenceable:
1386 llvm_unreachable("dereferenceable attribute not supported in raw format");
1387 break;
1388 case Attribute::DereferenceableOrNull:
1389 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1390 "format");
1391 break;
1392 case Attribute::ArgMemOnly:
1393 llvm_unreachable("argmemonly attribute not supported in raw format");
1394 break;
1395 case Attribute::AllocSize:
1396 llvm_unreachable("allocsize not supported in raw format");
1397 break;
1398 }
1399 llvm_unreachable("Unsupported attribute type");
1400}
1401
1402static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1403 if (!Val) return;
1404
1405 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1406 I = Attribute::AttrKind(I + 1)) {
1407 if (I == Attribute::Dereferenceable ||
1408 I == Attribute::DereferenceableOrNull ||
1409 I == Attribute::ArgMemOnly ||
1410 I == Attribute::AllocSize)
1411 continue;
1412 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1413 if (I == Attribute::Alignment)
1414 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1415 else if (I == Attribute::StackAlignment)
1416 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1417 else
1418 B.addAttribute(I);
1419 }
1420 }
1421}
1422
Bill Wendling56aeccc2013-02-04 23:32:23 +00001423/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1424/// been decoded from the given integer. This function must stay in sync with
1425/// 'encodeLLVMAttributesForBitcode'.
1426static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1427 uint64_t EncodedAttrs) {
1428 // FIXME: Remove in 4.0.
1429
1430 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1431 // the bits above 31 down by 11 bits.
1432 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1433 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1434 "Alignment must be a power of two.");
1435
1436 if (Alignment)
1437 B.addAlignmentAttr(Alignment);
Amaury Sechet74084c42016-11-06 07:48:46 +00001438 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1439 (EncodedAttrs & 0xffff));
Bill Wendling56aeccc2013-02-04 23:32:23 +00001440}
1441
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001442std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001443 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001444 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001445
Devang Patela05633e2008-09-26 22:53:05 +00001446 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001447 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001448
Chris Lattnerfee5a372007-05-04 03:30:17 +00001449 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001450
Bill Wendling71173cb2013-01-27 00:36:48 +00001451 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001452
Chris Lattnerfee5a372007-05-04 03:30:17 +00001453 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001454 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001455 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001456
Chris Lattner27d38752013-01-20 02:13:19 +00001457 switch (Entry.Kind) {
1458 case BitstreamEntry::SubBlock: // Handled for us already.
1459 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001460 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001461 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001462 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001463 case BitstreamEntry::Record:
1464 // The interesting case.
1465 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001466 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001467
Chris Lattnerfee5a372007-05-04 03:30:17 +00001468 // Read a record.
1469 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001470 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001471 default: // Default behavior: ignore.
1472 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001473 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1474 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001475 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001476 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001477
Chris Lattnerfee5a372007-05-04 03:30:17 +00001478 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001479 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001480 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001481 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001482 }
Devang Patela05633e2008-09-26 22:53:05 +00001483
Bill Wendlinge94d8432012-12-07 23:16:57 +00001484 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001485 Attrs.clear();
1486 break;
1487 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001488 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1489 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1490 Attrs.push_back(MAttributeGroups[Record[i]]);
1491
1492 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1493 Attrs.clear();
1494 break;
1495 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001496 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001497 }
1498}
1499
Reid Klecknere9f36af2013-11-12 01:31:00 +00001500// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001501static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001502 switch (Code) {
1503 default:
1504 return Attribute::None;
1505 case bitc::ATTR_KIND_ALIGNMENT:
1506 return Attribute::Alignment;
1507 case bitc::ATTR_KIND_ALWAYS_INLINE:
1508 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001509 case bitc::ATTR_KIND_ARGMEMONLY:
1510 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001511 case bitc::ATTR_KIND_BUILTIN:
1512 return Attribute::Builtin;
1513 case bitc::ATTR_KIND_BY_VAL:
1514 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001515 case bitc::ATTR_KIND_IN_ALLOCA:
1516 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001517 case bitc::ATTR_KIND_COLD:
1518 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001519 case bitc::ATTR_KIND_CONVERGENT:
1520 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001521 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1522 return Attribute::InaccessibleMemOnly;
1523 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1524 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001525 case bitc::ATTR_KIND_INLINE_HINT:
1526 return Attribute::InlineHint;
1527 case bitc::ATTR_KIND_IN_REG:
1528 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001529 case bitc::ATTR_KIND_JUMP_TABLE:
1530 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001531 case bitc::ATTR_KIND_MIN_SIZE:
1532 return Attribute::MinSize;
1533 case bitc::ATTR_KIND_NAKED:
1534 return Attribute::Naked;
1535 case bitc::ATTR_KIND_NEST:
1536 return Attribute::Nest;
1537 case bitc::ATTR_KIND_NO_ALIAS:
1538 return Attribute::NoAlias;
1539 case bitc::ATTR_KIND_NO_BUILTIN:
1540 return Attribute::NoBuiltin;
1541 case bitc::ATTR_KIND_NO_CAPTURE:
1542 return Attribute::NoCapture;
1543 case bitc::ATTR_KIND_NO_DUPLICATE:
1544 return Attribute::NoDuplicate;
1545 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1546 return Attribute::NoImplicitFloat;
1547 case bitc::ATTR_KIND_NO_INLINE:
1548 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001549 case bitc::ATTR_KIND_NO_RECURSE:
1550 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001551 case bitc::ATTR_KIND_NON_LAZY_BIND:
1552 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001553 case bitc::ATTR_KIND_NON_NULL:
1554 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001555 case bitc::ATTR_KIND_DEREFERENCEABLE:
1556 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001557 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1558 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001559 case bitc::ATTR_KIND_ALLOC_SIZE:
1560 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001561 case bitc::ATTR_KIND_NO_RED_ZONE:
1562 return Attribute::NoRedZone;
1563 case bitc::ATTR_KIND_NO_RETURN:
1564 return Attribute::NoReturn;
1565 case bitc::ATTR_KIND_NO_UNWIND:
1566 return Attribute::NoUnwind;
1567 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1568 return Attribute::OptimizeForSize;
1569 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1570 return Attribute::OptimizeNone;
1571 case bitc::ATTR_KIND_READ_NONE:
1572 return Attribute::ReadNone;
1573 case bitc::ATTR_KIND_READ_ONLY:
1574 return Attribute::ReadOnly;
1575 case bitc::ATTR_KIND_RETURNED:
1576 return Attribute::Returned;
1577 case bitc::ATTR_KIND_RETURNS_TWICE:
1578 return Attribute::ReturnsTwice;
1579 case bitc::ATTR_KIND_S_EXT:
1580 return Attribute::SExt;
1581 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1582 return Attribute::StackAlignment;
1583 case bitc::ATTR_KIND_STACK_PROTECT:
1584 return Attribute::StackProtect;
1585 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1586 return Attribute::StackProtectReq;
1587 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1588 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001589 case bitc::ATTR_KIND_SAFESTACK:
1590 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001591 case bitc::ATTR_KIND_STRUCT_RET:
1592 return Attribute::StructRet;
1593 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1594 return Attribute::SanitizeAddress;
1595 case bitc::ATTR_KIND_SANITIZE_THREAD:
1596 return Attribute::SanitizeThread;
1597 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1598 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001599 case bitc::ATTR_KIND_SWIFT_ERROR:
1600 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001601 case bitc::ATTR_KIND_SWIFT_SELF:
1602 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001603 case bitc::ATTR_KIND_UW_TABLE:
1604 return Attribute::UWTable;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001605 case bitc::ATTR_KIND_WRITEONLY:
1606 return Attribute::WriteOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001607 case bitc::ATTR_KIND_Z_EXT:
1608 return Attribute::ZExt;
1609 }
1610}
1611
JF Bastien30bf96b2015-02-22 19:32:03 +00001612std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1613 unsigned &Alignment) {
1614 // Note: Alignment in bitcode files is incremented by 1, so that zero
1615 // can be used for default alignment.
1616 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001617 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001618 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1619 return std::error_code();
1620}
1621
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001622std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001623 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001624 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001625 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001626 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001627 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001628 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001629}
1630
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001631std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001632 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001633 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001634
1635 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001636 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001637
1638 SmallVector<uint64_t, 64> Record;
1639
1640 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001641 while (true) {
Bill Wendlingba629332013-02-10 23:24:25 +00001642 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1643
1644 switch (Entry.Kind) {
1645 case BitstreamEntry::SubBlock: // Handled for us already.
1646 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001647 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001648 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001649 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001650 case BitstreamEntry::Record:
1651 // The interesting case.
1652 break;
1653 }
1654
1655 // Read a record.
1656 Record.clear();
1657 switch (Stream.readRecord(Entry.ID, Record)) {
1658 default: // Default behavior: ignore.
1659 break;
1660 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1661 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001662 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001663
Bill Wendlinge46707e2013-02-11 22:32:29 +00001664 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001665 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1666
1667 AttrBuilder B;
1668 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1669 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001670 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001671 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001672 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001673
1674 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001675 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001676 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001677 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001678 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001679 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001680 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001681 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001682 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001683 else if (Kind == Attribute::Dereferenceable)
1684 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001685 else if (Kind == Attribute::DereferenceableOrNull)
1686 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001687 else if (Kind == Attribute::AllocSize)
1688 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001689 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001690 assert((Record[i] == 3 || Record[i] == 4) &&
1691 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001692 bool HasValue = (Record[i++] == 4);
1693 SmallString<64> KindStr;
1694 SmallString<64> ValStr;
1695
1696 while (Record[i] != 0 && i != e)
1697 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001698 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001699
1700 if (HasValue) {
1701 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001702 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001703 while (Record[i] != 0 && i != e)
1704 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001705 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001706 }
1707
1708 B.addAttribute(KindStr.str(), ValStr.str());
1709 }
1710 }
1711
Bill Wendlinge46707e2013-02-11 22:32:29 +00001712 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001713 break;
1714 }
1715 }
1716 }
1717}
1718
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001719std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001720 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001721 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001722
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001723 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001724}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001725
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001726std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001727 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001728 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001729
1730 SmallVector<uint64_t, 64> Record;
1731 unsigned NumRecords = 0;
1732
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001733 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001734
Chris Lattner1314b992007-04-22 06:23:29 +00001735 // Read all the records for this type table.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001736 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001737 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001738
Chris Lattner27d38752013-01-20 02:13:19 +00001739 switch (Entry.Kind) {
1740 case BitstreamEntry::SubBlock: // Handled for us already.
1741 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001742 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001743 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001744 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001745 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001746 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001747 case BitstreamEntry::Record:
1748 // The interesting case.
1749 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001750 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001751
Chris Lattner1314b992007-04-22 06:23:29 +00001752 // Read a record.
1753 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001754 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001755 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001756 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001757 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001758 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1759 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1760 // type list. This allows us to reserve space.
1761 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001762 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001763 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001764 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001765 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001766 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001767 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001768 case bitc::TYPE_CODE_HALF: // HALF
1769 ResultTy = Type::getHalfTy(Context);
1770 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001771 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001772 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001773 break;
1774 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001775 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001776 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001777 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001778 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001779 break;
1780 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001781 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001782 break;
1783 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001784 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001785 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001786 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001787 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001788 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001789 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001790 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001791 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001792 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1793 ResultTy = Type::getX86_MMXTy(Context);
1794 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001795 case bitc::TYPE_CODE_TOKEN: // TOKEN
1796 ResultTy = Type::getTokenTy(Context);
1797 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001798 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001799 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001800 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001801
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001802 uint64_t NumBits = Record[0];
1803 if (NumBits < IntegerType::MIN_INT_BITS ||
1804 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001805 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001806 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001807 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001809 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001810 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001811 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001812 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001813 unsigned AddressSpace = 0;
1814 if (Record.size() == 2)
1815 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001816 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001817 if (!ResultTy ||
1818 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001819 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001821 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001822 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001823 case bitc::TYPE_CODE_FUNCTION_OLD: {
1824 // FIXME: attrid is dead, remove it in LLVM 4.0
1825 // FUNCTION: [vararg, attrid, retty, paramty x N]
1826 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001827 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001828 SmallVector<Type*, 8> ArgTys;
1829 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1830 if (Type *T = getTypeByID(Record[i]))
1831 ArgTys.push_back(T);
1832 else
1833 break;
1834 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001835
Nuno Lopes561dae02012-05-23 15:19:39 +00001836 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001837 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001838 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001839
1840 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1841 break;
1842 }
Chad Rosier95898722011-11-03 00:14:01 +00001843 case bitc::TYPE_CODE_FUNCTION: {
1844 // FUNCTION: [vararg, retty, paramty x N]
1845 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001846 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001847 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001848 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001849 if (Type *T = getTypeByID(Record[i])) {
1850 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001851 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001852 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001853 }
Chad Rosier95898722011-11-03 00:14:01 +00001854 else
1855 break;
1856 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001857
Chad Rosier95898722011-11-03 00:14:01 +00001858 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001859 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001860 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001861
1862 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1863 break;
1864 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001865 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001866 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001867 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001868 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001869 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1870 if (Type *T = getTypeByID(Record[i]))
1871 EltTys.push_back(T);
1872 else
1873 break;
1874 }
1875 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001876 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001877 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001878 break;
1879 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001880 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001881 if (convertToString(Record, 0, TypeName))
1882 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001883 continue;
1884
1885 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1886 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001887 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001888
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001889 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001890 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001891
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001892 // Check to see if this was forward referenced, if so fill in the temp.
1893 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1894 if (Res) {
1895 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001896 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001897 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001898 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001899 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001900
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001901 SmallVector<Type*, 8> EltTys;
1902 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1903 if (Type *T = getTypeByID(Record[i]))
1904 EltTys.push_back(T);
1905 else
1906 break;
1907 }
1908 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001909 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001910 Res->setBody(EltTys, Record[0]);
1911 ResultTy = Res;
1912 break;
1913 }
1914 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1915 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001916 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001917
1918 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001919 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001920
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001921 // Check to see if this was forward referenced, if so fill in the temp.
1922 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1923 if (Res) {
1924 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001925 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001926 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001927 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001928 TypeName.clear();
1929 ResultTy = Res;
1930 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001931 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001932 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1933 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001934 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001935 ResultTy = getTypeByID(Record[1]);
1936 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001937 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001938 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001939 break;
1940 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1941 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001942 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001943 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001944 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001945 ResultTy = getTypeByID(Record[1]);
1946 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001947 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001948 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001949 break;
1950 }
1951
1952 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001953 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001954 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001955 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001956 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001957 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001958 TypeList[NumRecords++] = ResultTy;
1959 }
1960}
1961
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001962std::error_code BitcodeReader::parseOperandBundleTags() {
1963 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1964 return error("Invalid record");
1965
1966 if (!BundleTags.empty())
1967 return error("Invalid multiple blocks");
1968
1969 SmallVector<uint64_t, 64> Record;
1970
Eugene Zelenko1804a772016-08-25 00:45:04 +00001971 while (true) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001972 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1973
1974 switch (Entry.Kind) {
1975 case BitstreamEntry::SubBlock: // Handled for us already.
1976 case BitstreamEntry::Error:
1977 return error("Malformed block");
1978 case BitstreamEntry::EndBlock:
1979 return std::error_code();
1980 case BitstreamEntry::Record:
1981 // The interesting case.
1982 break;
1983 }
1984
1985 // Tags are implicitly mapped to integers by their order.
1986
1987 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1988 return error("Invalid record");
1989
1990 // OPERAND_BUNDLE_TAG: [strchr x N]
1991 BundleTags.emplace_back();
1992 if (convertToString(Record, 0, BundleTags.back()))
1993 return error("Invalid record");
1994 Record.clear();
1995 }
1996}
1997
Teresa Johnsonff642b92015-09-17 20:12:00 +00001998/// Associate a value with its name from the given index in the provided record.
1999ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2000 unsigned NameIndex, Triple &TT) {
2001 SmallString<128> ValueName;
2002 if (convertToString(Record, NameIndex, ValueName))
2003 return error("Invalid record");
2004 unsigned ValueID = Record[0];
2005 if (ValueID >= ValueList.size() || !ValueList[ValueID])
2006 return error("Invalid record");
2007 Value *V = ValueList[ValueID];
2008
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00002009 StringRef NameStr(ValueName.data(), ValueName.size());
2010 if (NameStr.find_first_of(0) != StringRef::npos)
2011 return error("Invalid value name");
2012 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002013 auto *GO = dyn_cast<GlobalObject>(V);
2014 if (GO) {
2015 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
2016 if (TT.isOSBinFormatMachO())
2017 GO->setComdat(nullptr);
2018 else
2019 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2020 }
2021 }
2022 return V;
2023}
2024
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002025/// Helper to note and return the current location, and jump to the given
2026/// offset.
2027static uint64_t jumpToValueSymbolTable(uint64_t Offset,
2028 BitstreamCursor &Stream) {
2029 // Save the current parsing location so we can jump back at the end
2030 // of the VST read.
2031 uint64_t CurrentBit = Stream.GetCurrentBitNo();
2032 Stream.JumpToBit(Offset * 32);
2033#ifndef NDEBUG
2034 // Do some checking if we are in debug mode.
2035 BitstreamEntry Entry = Stream.advance();
2036 assert(Entry.Kind == BitstreamEntry::SubBlock);
2037 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
2038#else
2039 // In NDEBUG mode ignore the output so we don't get an unused variable
2040 // warning.
2041 Stream.advance();
2042#endif
2043 return CurrentBit;
2044}
2045
Teresa Johnsonff642b92015-09-17 20:12:00 +00002046/// Parse the value symbol table at either the current parsing location or
2047/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00002048std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002049 uint64_t CurrentBit;
2050 // Pass in the Offset to distinguish between calling for the module-level
2051 // VST (where we want to jump to the VST offset) and the function-level
2052 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002053 if (Offset > 0)
2054 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002055
2056 // Compute the delta between the bitcode indices in the VST (the word offset
2057 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2058 // expected by the lazy reader. The reader's EnterSubBlock expects to have
2059 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2060 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2061 // just before entering the VST subblock because: 1) the EnterSubBlock
2062 // changes the AbbrevID width; 2) the VST block is nested within the same
2063 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2064 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2065 // jump to the FUNCTION_BLOCK using this offset later, we don't want
2066 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2067 unsigned FuncBitcodeOffsetDelta =
2068 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2069
Chris Lattner982ec1e2007-05-05 00:17:00 +00002070 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002071 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00002072
2073 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002074
David Majnemer3087b222015-01-20 05:58:07 +00002075 Triple TT(TheModule->getTargetTriple());
2076
Chris Lattnerccaa4482007-04-23 21:26:05 +00002077 // Read all the records for this value table.
2078 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00002079
2080 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002081 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002082
Chris Lattner27d38752013-01-20 02:13:19 +00002083 switch (Entry.Kind) {
2084 case BitstreamEntry::SubBlock: // Handled for us already.
2085 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002086 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002087 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00002088 if (Offset > 0)
2089 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002090 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002091 case BitstreamEntry::Record:
2092 // The interesting case.
2093 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002094 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002095
Chris Lattnerccaa4482007-04-23 21:26:05 +00002096 // Read a record.
2097 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00002098 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00002099 default: // Default behavior: unknown type.
2100 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002101 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00002102 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
2103 if (std::error_code EC = ValOrErr.getError())
2104 return EC;
2105 ValOrErr.get();
2106 break;
2107 }
2108 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002109 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00002110 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
2111 if (std::error_code EC = ValOrErr.getError())
2112 return EC;
2113 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002114
Teresa Johnsonff642b92015-09-17 20:12:00 +00002115 auto *GO = dyn_cast<GlobalObject>(V);
2116 if (!GO) {
2117 // If this is an alias, need to get the actual Function object
2118 // it aliases, in order to set up the DeferredFunctionInfo entry below.
2119 auto *GA = dyn_cast<GlobalAlias>(V);
2120 if (GA)
2121 GO = GA->getBaseObject();
2122 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002123 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00002124
2125 uint64_t FuncWordOffset = Record[1];
2126 Function *F = dyn_cast<Function>(GO);
2127 assert(F);
2128 uint64_t FuncBitOffset = FuncWordOffset * 32;
2129 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00002130 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002131 // Later when parsing is resumed after function materialization,
2132 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00002133 if (FuncBitOffset > LastFunctionBlockBit)
2134 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002135 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00002136 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002137 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002138 if (convertToString(Record, 1, ValueName))
2139 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00002140 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002141 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002142 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002143
Daniel Dunbard786b512009-07-26 00:34:27 +00002144 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00002145 ValueName.clear();
2146 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002147 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00002148 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00002149 }
2150}
2151
Teresa Johnson12545072015-11-15 02:00:09 +00002152/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2153std::error_code
2154BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
2155 if (Record.size() < 2)
2156 return error("Invalid record");
2157
2158 unsigned Kind = Record[0];
2159 SmallString<8> Name(Record.begin() + 1, Record.end());
2160
2161 unsigned NewKind = TheModule->getMDKindID(Name.str());
2162 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2163 return error("Conflicting METADATA_KIND records");
2164 return std::error_code();
2165}
2166
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002167static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2168
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002169std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
2170 StringRef Blob,
2171 unsigned &NextMetadataNo) {
2172 // All the MDStrings in the block are emitted together in a single
2173 // record. The strings are concatenated and stored in a blob along with
2174 // their sizes.
2175 if (Record.size() != 2)
2176 return error("Invalid record: metadata strings layout");
2177
2178 unsigned NumStrings = Record[0];
2179 unsigned StringsOffset = Record[1];
2180 if (!NumStrings)
2181 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00002182 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002183 return error("Invalid record: metadata strings corrupt offset");
2184
2185 StringRef Lengths = Blob.slice(0, StringsOffset);
Peter Collingbourne77c89b62016-11-08 04:17:11 +00002186 SimpleBitstreamCursor R(Lengths);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002187
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002188 StringRef Strings = Blob.drop_front(StringsOffset);
2189 do {
2190 if (R.AtEndOfStream())
2191 return error("Invalid record: metadata strings bad length");
2192
2193 unsigned Size = R.ReadVBR(6);
2194 if (Strings.size() < Size)
2195 return error("Invalid record: metadata strings truncated chars");
2196
2197 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
2198 NextMetadataNo++);
2199 Strings = Strings.drop_front(Size);
2200 } while (--NumStrings);
2201
2202 return std::error_code();
2203}
2204
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002205namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +00002206
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002207class PlaceholderQueue {
2208 // Placeholders would thrash around when moved, so store in a std::deque
2209 // instead of some sort of vector.
2210 std::deque<DistinctMDOperandPlaceholder> PHs;
2211
2212public:
2213 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
2214 void flush(BitcodeReaderMetadataList &MetadataList);
2215};
Eugene Zelenko1804a772016-08-25 00:45:04 +00002216
2217} // end anonymous namespace
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002218
2219DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
2220 PHs.emplace_back(ID);
2221 return PHs.back();
2222}
2223
2224void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
2225 while (!PHs.empty()) {
2226 PHs.front().replaceUseWith(
2227 MetadataList.getMetadataFwdRef(PHs.front().getID()));
2228 PHs.pop_front();
2229 }
2230}
2231
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00002232/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
2233/// module level metadata.
2234std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00002235 assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
2236 "Must read all module-level metadata before function-level");
2237
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002238 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002239 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00002240
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00002241 if (!ModuleLevel && MetadataList.hasFwdRefs())
2242 return error("Invalid metadata: fwd refs into function blocks");
2243
Devang Patel7428d8a2009-07-22 17:43:22 +00002244 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002245 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Adrian Prantl75819ae2016-04-15 15:57:41 +00002247 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
Devang Patel7428d8a2009-07-22 17:43:22 +00002248 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002250 PlaceholderQueue Placeholders;
2251 bool IsDistinct;
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002252 auto getMD = [&](unsigned ID) -> Metadata * {
2253 if (!IsDistinct)
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002254 return MetadataList.getMetadataFwdRef(ID);
2255 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
2256 return MD;
2257 return &Placeholders.getPlaceholderOp(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002258 };
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002259 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002260 if (ID)
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002261 return getMD(ID - 1);
2262 return nullptr;
2263 };
2264 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
2265 if (ID)
2266 return MetadataList.getMetadataFwdRef(ID - 1);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002267 return nullptr;
2268 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002269 auto getMDString = [&](unsigned ID) -> MDString *{
2270 // This requires that the ID is not really a forward reference. In
2271 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002272 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002273 };
2274
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002275 // Support for old type refs.
2276 auto getDITypeRefOrNull = [&](unsigned ID) {
2277 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
2278 };
2279
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002280#define GET_OR_DISTINCT(CLASS, ARGS) \
2281 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002282
Devang Patel7428d8a2009-07-22 17:43:22 +00002283 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002284 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002285 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002286
Chris Lattner27d38752013-01-20 02:13:19 +00002287 switch (Entry.Kind) {
2288 case BitstreamEntry::SubBlock: // Handled for us already.
2289 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002290 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002291 case BitstreamEntry::EndBlock:
Adrian Prantl75819ae2016-04-15 15:57:41 +00002292 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
2293 for (auto CU_SP : CUSubprograms)
2294 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
2295 for (auto &Op : SPs->operands())
2296 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
2297 SP->replaceOperandWith(7, CU_SP.first);
2298
Teresa Johnson61b406e2015-12-29 23:00:22 +00002299 MetadataList.tryToResolveCycles();
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002300 Placeholders.flush(MetadataList);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002301 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002302 case BitstreamEntry::Record:
2303 // The interesting case.
2304 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002305 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002306
Devang Patel7428d8a2009-07-22 17:43:22 +00002307 // Read a record.
2308 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002309 StringRef Blob;
2310 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002311 IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00002312 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00002313 default: // Default behavior: ignore.
2314 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00002315 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00002316 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002317 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00002318 Record.clear();
2319 Code = Stream.ReadCode();
2320
Chris Lattner27d38752013-01-20 02:13:19 +00002321 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00002322 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002323 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00002324
2325 // Read named metadata elements.
2326 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00002327 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00002328 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00002329 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002330 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002331 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002332 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002333 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002334 break;
2335 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002336 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002337 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002338 // This is a LocalAsMetadata record, the only type of function-local
2339 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002340 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002341 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002342
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002343 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2344 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002345 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002346 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002347 };
2348 if (Record.size() != 2) {
2349 dropRecord();
2350 break;
2351 }
2352
2353 Type *Ty = getTypeByID(Record[0]);
2354 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2355 dropRecord();
2356 break;
2357 }
2358
Teresa Johnson61b406e2015-12-29 23:00:22 +00002359 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002360 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002361 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002362 break;
2363 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002364 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002365 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002366 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002367 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002368
Devang Patele059ba6e2009-07-23 01:07:34 +00002369 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002370 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002371 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002372 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002373 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002374 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002375 if (Ty->isMetadataTy())
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002376 Elts.push_back(getMD(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002377 else if (!Ty->isVoidTy()) {
2378 auto *MD =
2379 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2380 assert(isa<ConstantAsMetadata>(MD) &&
2381 "Expected non-function-local metadata");
2382 Elts.push_back(MD);
2383 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002384 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002385 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002386 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002387 break;
2388 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002389 case bitc::METADATA_VALUE: {
2390 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002391 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002392
2393 Type *Ty = getTypeByID(Record[0]);
2394 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002395 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002396
Teresa Johnson61b406e2015-12-29 23:00:22 +00002397 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002398 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002399 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002400 break;
2401 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002402 case bitc::METADATA_DISTINCT_NODE:
2403 IsDistinct = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00002404 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002405 case bitc::METADATA_NODE: {
2406 SmallVector<Metadata *, 8> Elts;
2407 Elts.reserve(Record.size());
2408 for (unsigned ID : Record)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002409 Elts.push_back(getMDOrNull(ID));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002410 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2411 : MDNode::get(Context, Elts),
2412 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002413 break;
2414 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002415 case bitc::METADATA_LOCATION: {
2416 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002417 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002418
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002419 IsDistinct = Record[0];
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002420 unsigned Line = Record[1];
2421 unsigned Column = Record[2];
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002422 Metadata *Scope = getMD(Record[3]);
2423 Metadata *InlinedAt = getMDOrNull(Record[4]);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002424 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002425 GET_OR_DISTINCT(DILocation,
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002426 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002427 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002428 break;
2429 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002430 case bitc::METADATA_GENERIC_DEBUG: {
2431 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002432 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002433
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002434 IsDistinct = Record[0];
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002435 unsigned Tag = Record[1];
2436 unsigned Version = Record[2];
2437
2438 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002439 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002440
2441 auto *Header = getMDString(Record[3]);
2442 SmallVector<Metadata *, 8> DwarfOps;
2443 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002444 DwarfOps.push_back(getMDOrNull(Record[I]));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002445 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002446 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002447 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002448 break;
2449 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002450 case bitc::METADATA_SUBRANGE: {
2451 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002452 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002453
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002454 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002455 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002456 GET_OR_DISTINCT(DISubrange,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002457 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002458 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002459 break;
2460 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002461 case bitc::METADATA_ENUMERATOR: {
2462 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002463 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002464
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002465 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002466 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002467 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
2468 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002469 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002470 break;
2471 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002472 case bitc::METADATA_BASIC_TYPE: {
2473 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002474 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002475
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002476 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002477 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002478 GET_OR_DISTINCT(DIBasicType,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002479 (Context, Record[1], getMDString(Record[2]),
2480 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002481 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002482 break;
2483 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002484 case bitc::METADATA_DERIVED_TYPE: {
2485 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002486 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002487
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002488 IsDistinct = Record[0];
Leny Kholodov5fcc4182016-09-06 10:46:28 +00002489 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002490 MetadataList.assignValue(
Leny Kholodov40c62352016-09-06 17:03:02 +00002491 GET_OR_DISTINCT(DIDerivedType,
2492 (Context, Record[1], getMDString(Record[2]),
2493 getMDOrNull(Record[3]), Record[4],
2494 getDITypeRefOrNull(Record[5]),
2495 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2496 Record[9], Flags, getDITypeRefOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002497 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002498 break;
2499 }
2500 case bitc::METADATA_COMPOSITE_TYPE: {
2501 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002502 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002503
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002504 // If we have a UUID and this is not a forward declaration, lookup the
2505 // mapping.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002506 IsDistinct = Record[0] & 0x1;
2507 bool IsNotUsedInTypeRef = Record[0] >= 2;
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002508 unsigned Tag = Record[1];
2509 MDString *Name = getMDString(Record[2]);
2510 Metadata *File = getMDOrNull(Record[3]);
2511 unsigned Line = Record[4];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002512 Metadata *Scope = getDITypeRefOrNull(Record[5]);
2513 Metadata *BaseType = getDITypeRefOrNull(Record[6]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002514 uint64_t SizeInBits = Record[7];
Victor Leschuk197aa312016-10-18 14:31:22 +00002515 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2516 return error("Alignment value is too large");
2517 uint32_t AlignInBits = Record[8];
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002518 uint64_t OffsetInBits = Record[9];
Leny Kholodov5fcc4182016-09-06 10:46:28 +00002519 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002520 Metadata *Elements = getMDOrNull(Record[11]);
2521 unsigned RuntimeLang = Record[12];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002522 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002523 Metadata *TemplateParams = getMDOrNull(Record[14]);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002524 auto *Identifier = getMDString(Record[15]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002525 DICompositeType *CT = nullptr;
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00002526 if (Identifier)
2527 CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002528 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2529 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2530 VTableHolder, TemplateParams);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002531
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002532 // Create a node if we didn't get a lazy ODR type.
2533 if (!CT)
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002534 CT = GET_OR_DISTINCT(DICompositeType,
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002535 (Context, Tag, Name, File, Line, Scope, BaseType,
2536 SizeInBits, AlignInBits, OffsetInBits, Flags,
2537 Elements, RuntimeLang, VTableHolder,
2538 TemplateParams, Identifier));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002539 if (!IsNotUsedInTypeRef && Identifier)
2540 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002541
2542 MetadataList.assignValue(CT, NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002543 break;
2544 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002545 case bitc::METADATA_SUBROUTINE_TYPE: {
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002546 if (Record.size() < 3 || Record.size() > 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002547 return error("Invalid record");
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002548 bool IsOldTypeRefArray = Record[0] < 2;
2549 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002550
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002551 IsDistinct = Record[0] & 0x1;
Leny Kholodov5fcc4182016-09-06 10:46:28 +00002552 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002553 Metadata *Types = getMDOrNull(Record[2]);
2554 if (LLVM_UNLIKELY(IsOldTypeRefArray))
2555 Types = MetadataList.upgradeTypeRefArray(Types);
2556
Teresa Johnson61b406e2015-12-29 23:00:22 +00002557 MetadataList.assignValue(
Leny Kholodov5fcc4182016-09-06 10:46:28 +00002558 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002559 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002560 break;
2561 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002562
2563 case bitc::METADATA_MODULE: {
2564 if (Record.size() != 6)
2565 return error("Invalid record");
2566
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002567 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002568 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002569 GET_OR_DISTINCT(DIModule,
Adrian Prantlab1243f2015-06-29 23:03:47 +00002570 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002571 getMDString(Record[2]), getMDString(Record[3]),
2572 getMDString(Record[4]), getMDString(Record[5]))),
2573 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002574 break;
2575 }
2576
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002577 case bitc::METADATA_FILE: {
2578 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002579 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002580
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002581 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002582 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002583 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2584 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002585 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002586 break;
2587 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002588 case bitc::METADATA_COMPILE_UNIT: {
David Blaikiea01f2952016-08-24 18:29:49 +00002589 if (Record.size() < 14 || Record.size() > 17)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002590 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002591
Amjad Abouda9bcf162015-12-10 12:56:35 +00002592 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002593 // distinct. It's always distinct.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002594 IsDistinct = true;
Adrian Prantl75819ae2016-04-15 15:57:41 +00002595 auto *CU = DICompileUnit::getDistinct(
2596 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2597 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2598 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2599 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2600 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
David Blaikiea01f2952016-08-24 18:29:49 +00002601 Record.size() <= 14 ? 0 : Record[14],
2602 Record.size() <= 16 ? true : Record[16]);
Adrian Prantl75819ae2016-04-15 15:57:41 +00002603
2604 MetadataList.assignValue(CU, NextMetadataNo++);
2605
2606 // Move the Upgrade the list of subprograms.
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002607 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
Adrian Prantl75819ae2016-04-15 15:57:41 +00002608 CUSubprograms.push_back({CU, SPs});
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002609 break;
2610 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002611 case bitc::METADATA_SUBPROGRAM: {
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002612 if (Record.size() < 18 || Record.size() > 20)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002613 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002614
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002615 IsDistinct =
Adrian Prantl85338cb2016-05-06 22:53:06 +00002616 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002617 // Version 1 has a Function as Record[15].
2618 // Version 2 has removed Record[15].
2619 // Version 3 has the Unit as Record[15].
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002620 // Version 4 added thisAdjustment.
Adrian Prantl85338cb2016-05-06 22:53:06 +00002621 bool HasUnit = Record[0] >= 2;
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002622 if (HasUnit && Record.size() < 19)
Adrian Prantl85338cb2016-05-06 22:53:06 +00002623 return error("Invalid record");
Adrian Prantl75819ae2016-04-15 15:57:41 +00002624 Metadata *CUorFn = getMDOrNull(Record[15]);
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002625 unsigned Offset = Record.size() >= 19 ? 1 : 0;
Adrian Prantl85338cb2016-05-06 22:53:06 +00002626 bool HasFn = Offset && !HasUnit;
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002627 bool HasThisAdj = Record.size() >= 20;
Peter Collingbourned4bff302015-11-05 22:03:56 +00002628 DISubprogram *SP = GET_OR_DISTINCT(
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002629 DISubprogram, (Context,
Leny Kholodov40c62352016-09-06 17:03:02 +00002630 getDITypeRefOrNull(Record[1]), // scope
2631 getMDString(Record[2]), // name
2632 getMDString(Record[3]), // linkageName
2633 getMDOrNull(Record[4]), // file
2634 Record[5], // line
2635 getMDOrNull(Record[6]), // type
2636 Record[7], // isLocal
2637 Record[8], // isDefinition
2638 Record[9], // scopeLine
2639 getDITypeRefOrNull(Record[10]), // containingType
2640 Record[11], // virtuality
2641 Record[12], // virtualIndex
2642 HasThisAdj ? Record[19] : 0, // thisAdjustment
2643 static_cast<DINode::DIFlags>(Record[13] // flags
2644 ),
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002645 Record[14], // isOptimized
2646 HasUnit ? CUorFn : nullptr, // unit
2647 getMDOrNull(Record[15 + Offset]), // templateParams
2648 getMDOrNull(Record[16 + Offset]), // declaration
2649 getMDOrNull(Record[17 + Offset]) // variables
2650 ));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002651 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002652
2653 // Upgrade sp->function mapping to function->sp mapping.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002654 if (HasFn) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00002655 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
Peter Collingbourned4bff302015-11-05 22:03:56 +00002656 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2657 if (F->isMaterializable())
2658 // Defer until materialized; unmaterialized functions may not have
2659 // metadata.
2660 FunctionsWithSPs[F] = SP;
2661 else if (!F->empty())
2662 F->setSubprogram(SP);
2663 }
2664 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002665 break;
2666 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002667 case bitc::METADATA_LEXICAL_BLOCK: {
2668 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002669 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002670
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002671 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002672 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002673 GET_OR_DISTINCT(DILexicalBlock,
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002674 (Context, getMDOrNull(Record[1]),
2675 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002676 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002677 break;
2678 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002679 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2680 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002681 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002682
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002683 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002684 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002685 GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002686 (Context, getMDOrNull(Record[1]),
2687 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002688 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002689 break;
2690 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002691 case bitc::METADATA_NAMESPACE: {
2692 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002693 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002694
Adrian Prantldbfda632016-11-03 19:42:02 +00002695 IsDistinct = Record[0] & 1;
2696 bool ExportSymbols = Record[0] & 2;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002697 MetadataList.assignValue(
Adrian Prantldbfda632016-11-03 19:42:02 +00002698 GET_OR_DISTINCT(DINamespace,
2699 (Context, getMDOrNull(Record[1]),
2700 getMDOrNull(Record[2]), getMDString(Record[3]),
2701 Record[4], ExportSymbols)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002702 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002703 break;
2704 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002705 case bitc::METADATA_MACRO: {
2706 if (Record.size() != 5)
2707 return error("Invalid record");
2708
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002709 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002710 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002711 GET_OR_DISTINCT(DIMacro,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002712 (Context, Record[1], Record[2],
2713 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002714 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002715 break;
2716 }
2717 case bitc::METADATA_MACRO_FILE: {
2718 if (Record.size() != 5)
2719 return error("Invalid record");
2720
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002721 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002722 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002723 GET_OR_DISTINCT(DIMacroFile,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002724 (Context, Record[1], Record[2],
2725 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002726 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002727 break;
2728 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002729 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002730 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002731 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002732
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002733 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002734 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Teresa Johnson61b406e2015-12-29 23:00:22 +00002735 (Context, getMDString(Record[1]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002736 getDITypeRefOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002737 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002738 break;
2739 }
2740 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002741 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002742 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002743
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002744 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002745 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002746 GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002747 (Context, Record[1], getMDString(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002748 getDITypeRefOrNull(Record[3]),
2749 getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002750 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002751 break;
2752 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002753 case bitc::METADATA_GLOBAL_VAR: {
Victor Leschuk2ede1262016-10-20 00:13:12 +00002754 if (Record.size() < 11 || Record.size() > 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002755 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002756
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002757 IsDistinct = Record[0];
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002758
2759 // Upgrade old metadata, which stored a global variable reference or a
2760 // ConstantInt here.
2761 Metadata *Expr = getMDOrNull(Record[9]);
Victor Leschuka37660c2016-10-26 21:32:29 +00002762 uint32_t AlignInBits = 0;
2763 if (Record.size() > 11) {
2764 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2765 return error("Alignment value is too large");
2766 AlignInBits = Record[11];
2767 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002768 GlobalVariable *Attach = nullptr;
2769 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2770 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2771 Attach = GV;
2772 Expr = nullptr;
2773 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
2774 Expr = DIExpression::get(Context,
2775 {dwarf::DW_OP_constu, CI->getZExtValue(),
2776 dwarf::DW_OP_stack_value});
2777 } else {
2778 Expr = nullptr;
2779 }
2780 }
2781
2782 DIGlobalVariable *DGV = GET_OR_DISTINCT(
2783 DIGlobalVariable,
2784 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2785 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2786 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Expr,
Victor Leschuk2ede1262016-10-20 00:13:12 +00002787 getMDOrNull(Record[10]), AlignInBits));
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002788 MetadataList.assignValue(DGV, NextMetadataNo++);
2789
2790 if (Attach)
2791 Attach->addDebugInfo(DGV);
2792
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002793 break;
2794 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002795 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002796 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002797 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002798 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002799
Victor Leschuk2ede1262016-10-20 00:13:12 +00002800 IsDistinct = Record[0] & 1;
2801 bool HasAlignment = Record[0] & 2;
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002802 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
Victor Leschuk2ede1262016-10-20 00:13:12 +00002803 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
2804 // this is newer version of record which doesn't have artifical tag.
2805 bool HasTag = !HasAlignment && Record.size() > 8;
Leny Kholodov5fcc4182016-09-06 10:46:28 +00002806 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
Victor Leschuka37660c2016-10-26 21:32:29 +00002807 uint32_t AlignInBits = 0;
2808 if (HasAlignment) {
2809 if (Record[8 + HasTag] >
2810 (uint64_t)std::numeric_limits<uint32_t>::max())
2811 return error("Alignment value is too large");
2812 AlignInBits = Record[8 + HasTag];
2813 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002814 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002815 GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002816 (Context, getMDOrNull(Record[1 + HasTag]),
2817 getMDString(Record[2 + HasTag]),
2818 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002819 getDITypeRefOrNull(Record[5 + HasTag]),
Victor Leschuk2ede1262016-10-20 00:13:12 +00002820 Record[6 + HasTag], Flags, AlignInBits)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002821 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002822 break;
2823 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002824 case bitc::METADATA_EXPRESSION: {
2825 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002826 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002827
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002828 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002829 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002830 GET_OR_DISTINCT(DIExpression,
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002831 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002832 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002833 break;
2834 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002835 case bitc::METADATA_OBJC_PROPERTY: {
2836 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002837 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002838
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002839 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002840 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002841 GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002842 (Context, getMDString(Record[1]),
2843 getMDOrNull(Record[2]), Record[3],
2844 getMDString(Record[4]), getMDString(Record[5]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002845 Record[6], getDITypeRefOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002846 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002847 break;
2848 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002849 case bitc::METADATA_IMPORTED_ENTITY: {
2850 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002851 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002852
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002853 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002854 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002855 GET_OR_DISTINCT(DIImportedEntity,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002856 (Context, Record[1], getMDOrNull(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002857 getDITypeRefOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002858 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002859 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002860 break;
2861 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002862 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002863 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002864
2865 // Test for upgrading !llvm.loop.
2866 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2867
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002868 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002869 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002870 break;
2871 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002872 case bitc::METADATA_STRINGS:
2873 if (std::error_code EC =
2874 parseMetadataStrings(Record, Blob, NextMetadataNo))
2875 return EC;
2876 break;
Peter Collingbourne21521892016-06-21 23:42:48 +00002877 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2878 if (Record.size() % 2 == 0)
2879 return error("Invalid record");
2880 unsigned ValueID = Record[0];
2881 if (ValueID >= ValueList.size())
2882 return error("Invalid record");
2883 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2884 parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
2885 break;
2886 }
Devang Patelaf206b82009-09-18 19:26:43 +00002887 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002888 // Support older bitcode files that had METADATA_KIND records in a
2889 // block with METADATA_BLOCK_ID.
2890 if (std::error_code EC = parseMetadataKindRecord(Record))
2891 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002892 break;
2893 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002894 }
2895 }
Eugene Zelenko1804a772016-08-25 00:45:04 +00002896
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002897#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002898}
2899
Teresa Johnson12545072015-11-15 02:00:09 +00002900/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2901std::error_code BitcodeReader::parseMetadataKinds() {
2902 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2903 return error("Invalid record");
2904
2905 SmallVector<uint64_t, 64> Record;
2906
2907 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002908 while (true) {
Teresa Johnson12545072015-11-15 02:00:09 +00002909 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2910
2911 switch (Entry.Kind) {
2912 case BitstreamEntry::SubBlock: // Handled for us already.
2913 case BitstreamEntry::Error:
2914 return error("Malformed block");
2915 case BitstreamEntry::EndBlock:
2916 return std::error_code();
2917 case BitstreamEntry::Record:
2918 // The interesting case.
2919 break;
2920 }
2921
2922 // Read a record.
2923 Record.clear();
2924 unsigned Code = Stream.readRecord(Entry.ID, Record);
2925 switch (Code) {
2926 default: // Default behavior: ignore.
2927 break;
2928 case bitc::METADATA_KIND: {
2929 if (std::error_code EC = parseMetadataKindRecord(Record))
2930 return EC;
2931 break;
2932 }
2933 }
2934 }
2935}
2936
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002937/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2938/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002939uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002940 if ((V & 1) == 0)
2941 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002942 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002943 return -(V >> 1);
2944 // There is no such thing as -0 with integers. "-0" really means MININT.
2945 return 1ULL << 63;
2946}
2947
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002948/// Resolve all of the initializers for global values and aliases that we can.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002949std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002950 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002951 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2952 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002953 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002954 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002955 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002956
Chris Lattner44c17072007-04-26 02:46:40 +00002957 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002958 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002959 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002960 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002961 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002962
2963 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002964 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002965 if (ValID >= ValueList.size()) {
2966 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002967 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002968 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002969 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002970 GlobalInitWorklist.back().first->setInitializer(C);
2971 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002972 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002973 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002974 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002975 }
2976
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002977 while (!IndirectSymbolInitWorklist.empty()) {
2978 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002979 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002980 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002981 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002982 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2983 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002984 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002985 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2986 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002987 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002988 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002989 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002990 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002991 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002992
2993 while (!FunctionPrefixWorklist.empty()) {
2994 unsigned ValID = FunctionPrefixWorklist.back().second;
2995 if (ValID >= ValueList.size()) {
2996 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2997 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002998 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002999 FunctionPrefixWorklist.back().first->setPrefixData(C);
3000 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003001 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003002 }
3003 FunctionPrefixWorklist.pop_back();
3004 }
3005
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003006 while (!FunctionPrologueWorklist.empty()) {
3007 unsigned ValID = FunctionPrologueWorklist.back().second;
3008 if (ValID >= ValueList.size()) {
3009 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
3010 } else {
3011 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
3012 FunctionPrologueWorklist.back().first->setPrologueData(C);
3013 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003014 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003015 }
3016 FunctionPrologueWorklist.pop_back();
3017 }
3018
David Majnemer7fddecc2015-06-17 20:52:32 +00003019 while (!FunctionPersonalityFnWorklist.empty()) {
3020 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
3021 if (ValID >= ValueList.size()) {
3022 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
3023 } else {
3024 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
3025 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
3026 else
3027 return error("Expected a constant");
3028 }
3029 FunctionPersonalityFnWorklist.pop_back();
3030 }
3031
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003032 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00003033}
3034
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003035static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003036 SmallVector<uint64_t, 8> Words(Vals.size());
David Majnemer2d006e72016-08-12 04:32:42 +00003037 transform(Vals, Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00003038 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003039
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003040 return APInt(TypeBits, Words);
3041}
3042
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003043std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003044 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003045 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003046
3047 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003048
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003049 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00003050 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00003051 unsigned NextCstNo = ValueList.size();
Eugene Zelenko1804a772016-08-25 00:45:04 +00003052
3053 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003054 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003055
Chris Lattner27d38752013-01-20 02:13:19 +00003056 switch (Entry.Kind) {
3057 case BitstreamEntry::SubBlock: // Handled for us already.
3058 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003059 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003060 case BitstreamEntry::EndBlock:
3061 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00003062 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00003063
Chris Lattner27d38752013-01-20 02:13:19 +00003064 // Once all the constants have been read, go through and resolve forward
3065 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003066 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003067 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003068 case BitstreamEntry::Record:
3069 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00003070 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003071 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003072
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003073 // Read a record.
3074 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00003075 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00003076 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003077 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003078 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003079 default: // Default behavior: unknown constant
3080 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00003081 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003082 break;
3083 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
3084 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003085 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00003086 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003087 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00003088 if (TypeList[Record[0]] == VoidType)
3089 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003090 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00003091 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003092 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00003093 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003094 break;
3095 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00003096 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003097 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003098 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00003099 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00003100 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00003101 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003102 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003103
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003104 APInt VInt =
3105 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003106 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003107
Chris Lattner08feb1e2007-04-24 04:04:35 +00003108 break;
3109 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003110 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00003111 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003112 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00003113 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00003114 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
3115 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00003116 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00003117 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
3118 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00003119 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00003120 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
3121 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00003122 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00003123 // Bits are not stored the same way as a normal i80 APInt, compensate.
3124 uint64_t Rearrange[2];
3125 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3126 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00003127 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
3128 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00003129 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00003130 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
3131 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00003132 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00003133 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
3134 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003135 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00003136 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003137 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003138 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003139
Chris Lattnere14cb882007-05-04 19:11:41 +00003140 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3141 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003142 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003143
Chris Lattnere14cb882007-05-04 19:11:41 +00003144 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00003145 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003146
Chris Lattner229907c2011-07-18 04:54:35 +00003147 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00003148 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00003149 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00003150 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00003151 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00003152 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
3153 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00003154 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00003155 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00003156 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00003157 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
3158 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00003159 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00003160 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00003161 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00003162 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003163 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00003164 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003165 break;
3166 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00003167 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00003168 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3169 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003170 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003171
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003172 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00003173 V = ConstantDataArray::getString(Context, Elts,
3174 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00003175 break;
3176 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00003177 case bitc::CST_CODE_DATA: {// DATA: [n x value]
3178 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003179 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003180
Chris Lattner372dd1e2012-01-30 00:51:16 +00003181 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00003182 if (EltTy->isIntegerTy(8)) {
3183 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3184 if (isa<VectorType>(CurTy))
3185 V = ConstantDataVector::get(Context, Elts);
3186 else
3187 V = ConstantDataArray::get(Context, Elts);
3188 } else if (EltTy->isIntegerTy(16)) {
3189 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3190 if (isa<VectorType>(CurTy))
3191 V = ConstantDataVector::get(Context, Elts);
3192 else
3193 V = ConstantDataArray::get(Context, Elts);
3194 } else if (EltTy->isIntegerTy(32)) {
3195 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3196 if (isa<VectorType>(CurTy))
3197 V = ConstantDataVector::get(Context, Elts);
3198 else
3199 V = ConstantDataArray::get(Context, Elts);
3200 } else if (EltTy->isIntegerTy(64)) {
3201 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3202 if (isa<VectorType>(CurTy))
3203 V = ConstantDataVector::get(Context, Elts);
3204 else
3205 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00003206 } else if (EltTy->isHalfTy()) {
3207 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3208 if (isa<VectorType>(CurTy))
3209 V = ConstantDataVector::getFP(Context, Elts);
3210 else
3211 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003212 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003213 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003214 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003215 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003216 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003217 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003218 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003219 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003220 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003221 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003222 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003223 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003224 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003225 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00003226 }
3227 break;
3228 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003229 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003230 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003231 return error("Invalid record");
3232 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003233 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003234 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00003235 } else {
3236 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3237 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00003238 unsigned Flags = 0;
3239 if (Record.size() >= 4) {
3240 if (Opc == Instruction::Add ||
3241 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003242 Opc == Instruction::Mul ||
3243 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00003244 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3245 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3246 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3247 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003248 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003249 Opc == Instruction::UDiv ||
3250 Opc == Instruction::LShr ||
3251 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003252 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003253 Flags |= SDivOperator::IsExact;
3254 }
3255 }
3256 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00003257 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003258 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003259 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003260 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003261 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003262 return error("Invalid record");
3263 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00003264 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003265 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00003266 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00003267 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003268 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003269 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00003270 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003271 V = UpgradeBitCastExpr(Opc, Op, CurTy);
3272 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003273 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003274 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003275 }
Dan Gohman1639c392009-07-27 21:53:46 +00003276 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003277 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00003278 unsigned OpNum = 0;
3279 Type *PointeeType = nullptr;
3280 if (Record.size() % 2)
3281 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003282 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00003283 while (OpNum != Record.size()) {
3284 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003285 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003286 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00003287 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003288 }
David Blaikieb9263572015-03-13 21:03:36 +00003289
David Blaikieb9263572015-03-13 21:03:36 +00003290 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00003291 PointeeType !=
3292 cast<SequentialType>(Elts[0]->getType()->getScalarType())
3293 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003294 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00003295 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003296
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00003297 if (Elts.size() < 1)
3298 return error("Invalid gep with no operands");
3299
David Blaikie4a2e73b2015-04-02 18:55:32 +00003300 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3301 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3302 BitCode ==
3303 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00003304 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003305 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00003306 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003307 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003308 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00003309
3310 Type *SelectorTy = Type::getInt1Ty(Context);
3311
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003312 // The selector might be an i1 or an <n x i1>
3313 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00003314 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003315 if (Value *V = ValueList[Record[0]])
3316 if (SelectorTy != V->getType())
3317 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00003318
3319 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3320 SelectorTy),
3321 ValueList.getConstantFwdRef(Record[1],CurTy),
3322 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003323 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00003324 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003325 case bitc::CST_CODE_CE_EXTRACTELT
3326 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003327 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003328 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003329 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003330 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003331 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003332 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003333 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003334 Constant *Op1 = nullptr;
3335 if (Record.size() == 4) {
3336 Type *IdxTy = getTypeByID(Record[2]);
3337 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003338 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003339 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3340 } else // TODO: Remove with llvm 4.0
3341 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3342 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003343 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003344 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003345 break;
3346 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003347 case bitc::CST_CODE_CE_INSERTELT
3348 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003349 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003350 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003351 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003352 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3353 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3354 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003355 Constant *Op2 = nullptr;
3356 if (Record.size() == 4) {
3357 Type *IdxTy = getTypeByID(Record[2]);
3358 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003359 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003360 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3361 } else // TODO: Remove with llvm 4.0
3362 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3363 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003364 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003365 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003366 break;
3367 }
3368 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003369 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003370 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003371 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003372 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3373 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003374 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003375 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003376 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003377 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003378 break;
3379 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00003380 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003381 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3382 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00003383 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003384 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003385 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00003386 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3387 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003388 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003389 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00003390 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003391 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00003392 break;
3393 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003394 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003395 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003396 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003397 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003398 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003399 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003400 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3401 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3402
Duncan Sands9dff9be2010-02-15 16:12:20 +00003403 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00003404 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00003405 else
Owen Anderson487375e2009-07-29 18:55:55 +00003406 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003407 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00003408 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003409 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00003410 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003411 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003412 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003413 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003414 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00003415 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003416 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003417 unsigned AsmStrSize = Record[1];
3418 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003419 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003420 unsigned ConstStrSize = Record[2+AsmStrSize];
3421 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003422 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003423
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003424 for (unsigned i = 0; i != AsmStrSize; ++i)
3425 AsmStr += (char)Record[2+i];
3426 for (unsigned i = 0; i != ConstStrSize; ++i)
3427 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00003428 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003429 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003430 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003431 break;
3432 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003433 // This version adds support for the asm dialect keywords (e.g.,
3434 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003435 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003436 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003437 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003438 std::string AsmStr, ConstrStr;
3439 bool HasSideEffects = Record[0] & 1;
3440 bool IsAlignStack = (Record[0] >> 1) & 1;
3441 unsigned AsmDialect = Record[0] >> 2;
3442 unsigned AsmStrSize = Record[1];
3443 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003444 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003445 unsigned ConstStrSize = Record[2+AsmStrSize];
3446 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003447 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003448
3449 for (unsigned i = 0; i != AsmStrSize; ++i)
3450 AsmStr += (char)Record[2+i];
3451 for (unsigned i = 0; i != ConstStrSize; ++i)
3452 ConstrStr += (char)Record[3+AsmStrSize+i];
3453 PointerType *PTy = cast<PointerType>(CurTy);
3454 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3455 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00003456 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003457 break;
3458 }
Chris Lattner5956dc82009-10-28 05:53:48 +00003459 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00003460 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003461 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003462 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003463 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003464 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00003465 Function *Fn =
3466 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00003467 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003468 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003469
3470 // If the function is already parsed we can insert the block address right
3471 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003472 BasicBlock *BB;
3473 unsigned BBID = Record[2];
3474 if (!BBID)
3475 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003476 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003477 if (!Fn->empty()) {
3478 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003479 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003480 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003481 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003482 ++BBI;
3483 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003484 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003485 } else {
3486 // Otherwise insert a placeholder and remember it so it can be inserted
3487 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003488 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3489 if (FwdBBs.empty())
3490 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003491 if (FwdBBs.size() < BBID + 1)
3492 FwdBBs.resize(BBID + 1);
3493 if (!FwdBBs[BBID])
3494 FwdBBs[BBID] = BasicBlock::Create(Context);
3495 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003496 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003497 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003498 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003499 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003500 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003501
David Majnemer8a1c45d2015-12-12 05:38:55 +00003502 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003503 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003504 }
3505}
Chris Lattner1314b992007-04-22 06:23:29 +00003506
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003507std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003508 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003509 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003510
Chad Rosierca2567b2011-12-07 21:44:12 +00003511 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003512 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00003513
3514 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003515 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003516
Chris Lattner27d38752013-01-20 02:13:19 +00003517 switch (Entry.Kind) {
3518 case BitstreamEntry::SubBlock: // Handled for us already.
3519 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003520 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003521 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003522 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003523 case BitstreamEntry::Record:
3524 // The interesting case.
3525 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003526 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003527
Chad Rosierca2567b2011-12-07 21:44:12 +00003528 // Read a use list record.
3529 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003530 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003531 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003532 default: // Default behavior: unknown type.
3533 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003534 case bitc::USELIST_CODE_BB:
3535 IsBB = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00003536 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003537 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003538 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003539 if (RecordLength < 3)
3540 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003541 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003542 unsigned ID = Record.back();
3543 Record.pop_back();
3544
3545 Value *V;
3546 if (IsBB) {
3547 assert(ID < FunctionBBs.size() && "Basic block not found");
3548 V = FunctionBBs[ID];
3549 } else
3550 V = ValueList[ID];
3551 unsigned NumUses = 0;
3552 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003553 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003554 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003555 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003556 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003557 }
3558 if (Order.size() != Record.size() || NumUses > Record.size())
3559 // Mismatches can happen if the functions are being materialized lazily
3560 // (out-of-order), or a value has been upgraded.
3561 break;
3562
3563 V->sortUseList([&](const Use &L, const Use &R) {
3564 return Order.lookup(&L) < Order.lookup(&R);
3565 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003566 break;
3567 }
3568 }
3569 }
3570}
3571
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003572/// When we see the block for metadata, remember where it is and then skip it.
3573/// This lets us lazily deserialize the metadata.
3574std::error_code BitcodeReader::rememberAndSkipMetadata() {
3575 // Save the current stream state.
3576 uint64_t CurBit = Stream.GetCurrentBitNo();
3577 DeferredMetadataInfo.push_back(CurBit);
3578
3579 // Skip over the block for now.
3580 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003581 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003582 return std::error_code();
3583}
3584
3585std::error_code BitcodeReader::materializeMetadata() {
3586 for (uint64_t BitPos : DeferredMetadataInfo) {
3587 // Move the bit stream to the saved position.
3588 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003589 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003590 return EC;
3591 }
3592 DeferredMetadataInfo.clear();
3593 return std::error_code();
3594}
3595
Rafael Espindola468b8682015-04-01 14:44:59 +00003596void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003597
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003598/// When we see the block for a function body, remember where it is and then
3599/// skip it. This lets us lazily deserialize the functions.
3600std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003601 // Get the function we are talking about.
3602 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003603 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003604
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003605 Function *Fn = FunctionsWithBodies.back();
3606 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003607
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003608 // Save the current stream state.
3609 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003610 assert(
3611 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3612 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003613 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003614
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003615 // Skip over the function block for now.
3616 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003617 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003618 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003619}
3620
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003621std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003622 // Patch the initializers for globals and aliases up.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003623 resolveGlobalAndIndirectSymbolInits();
3624 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003625 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003626
3627 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003628 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003629 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003630 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003631 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00003632 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3633 // Some types could be renamed during loading if several modules are
3634 // loaded in the same LLVMContext (LTO scenario). In this case we should
3635 // remangle intrinsics names as well.
3636 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003637 }
3638
3639 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003640 for (GlobalVariable &GV : TheModule->globals())
3641 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003642
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003643 // Force deallocation of memory for these vectors to favor the client that
3644 // want lazy deserialization.
3645 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003646 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3647 IndirectSymbolInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003648 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003649}
3650
Teresa Johnson1493ad92015-10-10 14:18:36 +00003651/// Support for lazy parsing of function bodies. This is required if we
3652/// either have an old bitcode file without a VST forward declaration record,
3653/// or if we have an anonymous function being materialized, since anonymous
3654/// functions do not have a name and are therefore not in the VST.
3655std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3656 Stream.JumpToBit(NextUnreadBit);
3657
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003658 if (Stream.AtEndOfStream())
3659 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003660
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003661 if (!SeenFirstFunctionBody)
3662 return error("Trying to materialize functions before seeing function blocks");
3663
Teresa Johnson1493ad92015-10-10 14:18:36 +00003664 // An old bitcode file with the symbol table at the end would have
3665 // finished the parse greedily.
3666 assert(SeenValueSymbolTable);
3667
3668 SmallVector<uint64_t, 64> Record;
3669
Eugene Zelenko1804a772016-08-25 00:45:04 +00003670 while (true) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003671 BitstreamEntry Entry = Stream.advance();
3672 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003673 default:
3674 return error("Expect SubBlock");
3675 case BitstreamEntry::SubBlock:
3676 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003677 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003678 return error("Expect function block");
3679 case bitc::FUNCTION_BLOCK_ID:
3680 if (std::error_code EC = rememberAndSkipFunctionBody())
3681 return EC;
3682 NextUnreadBit = Stream.GetCurrentBitNo();
3683 return std::error_code();
3684 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003685 }
3686 }
3687}
3688
Mehdi Amini5d303282015-10-26 18:37:00 +00003689std::error_code BitcodeReader::parseBitcodeVersion() {
3690 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3691 return error("Invalid record");
3692
3693 // Read all the records.
3694 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00003695
3696 while (true) {
Mehdi Amini5d303282015-10-26 18:37:00 +00003697 BitstreamEntry Entry = Stream.advance();
3698
3699 switch (Entry.Kind) {
3700 default:
3701 case BitstreamEntry::Error:
3702 return error("Malformed block");
3703 case BitstreamEntry::EndBlock:
3704 return std::error_code();
3705 case BitstreamEntry::Record:
3706 // The interesting case.
3707 break;
3708 }
3709
3710 // Read a record.
3711 Record.clear();
3712 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3713 switch (BitCode) {
3714 default: // Default behavior: reject
3715 return error("Invalid value");
3716 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3717 // N]
3718 convertToString(Record, 0, ProducerIdentification);
3719 break;
3720 }
3721 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3722 unsigned epoch = (unsigned)Record[0];
3723 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003724 return error(
3725 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3726 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003727 }
3728 }
3729 }
3730 }
3731}
3732
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003733bool BitcodeReaderBase::readBlockInfo() {
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003734 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
3735 if (!NewBlockInfo)
3736 return true;
3737 BlockInfo = std::move(*NewBlockInfo);
3738 return false;
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003739}
3740
Teresa Johnson1493ad92015-10-10 14:18:36 +00003741std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003742 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003743 if (ResumeBit)
3744 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003745 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003746 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003747
Chris Lattner1314b992007-04-22 06:23:29 +00003748 SmallVector<uint64_t, 64> Record;
3749 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003750 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003751
3752 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00003753 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003754 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003755
Chris Lattner27d38752013-01-20 02:13:19 +00003756 switch (Entry.Kind) {
3757 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003758 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003759 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003760 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003761
Chris Lattner27d38752013-01-20 02:13:19 +00003762 case BitstreamEntry::SubBlock:
3763 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003764 default: // Skip unknown content.
3765 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003766 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003767 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003768 case bitc::BLOCKINFO_BLOCK_ID:
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003769 if (readBlockInfo())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003770 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003771 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003772 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003773 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003774 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003775 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003776 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003777 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003778 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003779 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003780 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003781 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003782 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003783 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003784 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003785 if (!SeenValueSymbolTable) {
3786 // Either this is an old form VST without function index and an
3787 // associated VST forward declaration record (which would have caused
3788 // the VST to be jumped to and parsed before it was encountered
3789 // normally in the stream), or there were no function blocks to
3790 // trigger an earlier parsing of the VST.
3791 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3792 if (std::error_code EC = parseValueSymbolTable())
3793 return EC;
3794 SeenValueSymbolTable = true;
3795 } else {
3796 // We must have had a VST forward declaration record, which caused
3797 // the parser to jump to and parse the VST earlier.
3798 assert(VSTOffset > 0);
3799 if (Stream.SkipBlock())
3800 return error("Invalid record");
3801 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003802 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003803 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003804 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003805 return EC;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003806 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003807 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003808 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003809 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003810 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3811 if (std::error_code EC = rememberAndSkipMetadata())
3812 return EC;
3813 break;
3814 }
3815 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003816 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003817 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003818 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003819 case bitc::METADATA_KIND_BLOCK_ID:
3820 if (std::error_code EC = parseMetadataKinds())
3821 return EC;
3822 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003823 case bitc::FUNCTION_BLOCK_ID:
Mehdi Amini466a64e2016-08-13 23:39:14 +00003824 // If this is the first function body we've seen, reverse the
3825 // FunctionsWithBodies list.
3826 if (!SeenFirstFunctionBody) {
3827 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3828 if (std::error_code EC = globalCleanup())
3829 return EC;
3830 SeenFirstFunctionBody = true;
3831 }
3832
Teresa Johnsonff642b92015-09-17 20:12:00 +00003833 if (VSTOffset > 0) {
3834 // If we have a VST forward declaration record, make sure we
3835 // parse the VST now if we haven't already. It is needed to
3836 // set up the DeferredFunctionInfo vector for lazy reading.
3837 if (!SeenValueSymbolTable) {
3838 if (std::error_code EC =
3839 BitcodeReader::parseValueSymbolTable(VSTOffset))
3840 return EC;
3841 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003842 // Fall through so that we record the NextUnreadBit below.
3843 // This is necessary in case we have an anonymous function that
3844 // is later materialized. Since it will not have a VST entry we
3845 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003846 } else {
3847 // If we have a VST forward declaration record, but have already
3848 // parsed the VST (just above, when the first function body was
3849 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003850 // materializing functions. The ResumeBit points to the
3851 // start of the last function block recorded in the
3852 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003853 if (Stream.SkipBlock())
3854 return error("Invalid record");
3855 continue;
3856 }
3857 }
3858
3859 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003860 // index in the VST, nor a VST forward declaration record, as
3861 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003862 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003863 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003864 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003865
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003866 // Suspend parsing when we reach the function bodies. Subsequent
3867 // materialization calls will resume it when necessary. If the bitcode
3868 // file is old, the symbol table will be at the end instead and will not
3869 // have been seen yet. In this case, just finish the parse now.
3870 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003871 NextUnreadBit = Stream.GetCurrentBitNo();
Mehdi Aminia71002e2016-08-14 00:01:27 +00003872 // After the VST has been parsed, we need to make sure intrinsic name
3873 // are auto-upgraded.
3874 return globalCleanup();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003875 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003876 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003877 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003878 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003879 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003880 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003881 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3882 if (std::error_code EC = parseOperandBundleTags())
3883 return EC;
3884 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003885 }
3886 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003887
Chris Lattner27d38752013-01-20 02:13:19 +00003888 case BitstreamEntry::Record:
3889 // The interesting case.
3890 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003891 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003892
Chris Lattner1314b992007-04-22 06:23:29 +00003893 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003894 auto BitCode = Stream.readRecord(Entry.ID, Record);
3895 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003896 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003897 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003898 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003899 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003900 // Only version #0 and #1 are supported so far.
3901 unsigned module_version = Record[0];
3902 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003903 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003904 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003905 case 0:
3906 UseRelativeIDs = false;
3907 break;
3908 case 1:
3909 UseRelativeIDs = true;
3910 break;
3911 }
Chris Lattner1314b992007-04-22 06:23:29 +00003912 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003913 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003914 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003915 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003916 if (convertToString(Record, 0, S))
3917 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003918 TheModule->setTargetTriple(S);
3919 break;
3920 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003921 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003922 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003923 if (convertToString(Record, 0, S))
3924 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003925 TheModule->setDataLayout(S);
3926 break;
3927 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003928 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003929 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003930 if (convertToString(Record, 0, S))
3931 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003932 TheModule->setModuleInlineAsm(S);
3933 break;
3934 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003935 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3936 // FIXME: Remove in 4.0.
3937 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003938 if (convertToString(Record, 0, S))
3939 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003940 // Ignore value.
3941 break;
3942 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003943 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003944 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003945 if (convertToString(Record, 0, S))
3946 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003947 SectionTable.push_back(S);
3948 break;
3949 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003950 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003951 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003952 if (convertToString(Record, 0, S))
3953 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003954 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003955 break;
3956 }
David Majnemerdad0a642014-06-27 18:19:56 +00003957 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3958 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003959 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003960 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3961 unsigned ComdatNameSize = Record[1];
3962 std::string ComdatName;
3963 ComdatName.reserve(ComdatNameSize);
3964 for (unsigned i = 0; i != ComdatNameSize; ++i)
3965 ComdatName += (char)Record[2 + i];
3966 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3967 C->setSelectionKind(SK);
3968 ComdatList.push_back(C);
3969 break;
3970 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003971 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003972 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003973 // unnamed_addr, externally_initialized, dllstorageclass,
3974 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003975 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003976 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003977 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003978 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003979 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003980 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003981 bool isConstant = Record[1] & 1;
3982 bool explicitType = Record[1] & 2;
3983 unsigned AddressSpace;
3984 if (explicitType) {
3985 AddressSpace = Record[1] >> 2;
3986 } else {
3987 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003988 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003989 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3990 Ty = cast<PointerType>(Ty)->getElementType();
3991 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003992
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003993 uint64_t RawLinkage = Record[3];
3994 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003995 unsigned Alignment;
3996 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3997 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003998 std::string Section;
3999 if (Record[5]) {
4000 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004001 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00004002 Section = SectionTable[Record[5]-1];
4003 }
Chris Lattner4b00d922007-04-23 16:04:05 +00004004 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004005 // Local linkage must have default visibility.
4006 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
4007 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004008 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00004009
4010 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00004011 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004012 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00004013
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004014 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00004015 if (Record.size() > 8)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004016 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004017
Michael Gottesman27e7ef32013-02-05 05:57:38 +00004018 bool ExternallyInitialized = false;
4019 if (Record.size() > 9)
4020 ExternallyInitialized = Record[9];
4021
Chris Lattner1314b992007-04-22 06:23:29 +00004022 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00004023 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00004024 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00004025 NewGV->setAlignment(Alignment);
4026 if (!Section.empty())
4027 NewGV->setSection(Section);
4028 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004029 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004030
Nico Rieck7157bb72014-01-14 15:22:47 +00004031 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004032 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00004033 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004034 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00004035
Chris Lattnerccaa4482007-04-23 21:26:05 +00004036 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004037
Chris Lattner47d131b2007-04-24 00:18:21 +00004038 // Remember which value to use for the global initializer.
4039 if (unsigned InitID = Record[2])
4040 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00004041
Rafael Espindola12ca34f2015-01-19 15:16:06 +00004042 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00004043 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00004044 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004045 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00004046 NewGV->setComdat(ComdatList[ComdatID - 1]);
4047 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00004048 } else if (hasImplicitComdat(RawLinkage)) {
4049 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
4050 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004051
Chris Lattner1314b992007-04-22 06:23:29 +00004052 break;
4053 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00004054 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00004055 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004056 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00004057 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00004058 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004059 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004060 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004061 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004062 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00004063 if (auto *PTy = dyn_cast<PointerType>(Ty))
4064 Ty = PTy->getElementType();
4065 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00004066 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004067 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004068 auto CC = static_cast<CallingConv::ID>(Record[1]);
4069 if (CC & ~CallingConv::MaxID)
4070 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00004071
Gabor Greife9ecc682008-04-06 20:25:17 +00004072 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
4073 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00004074
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004075 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004076 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00004077 uint64_t RawLinkage = Record[3];
4078 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00004079 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004080
JF Bastien30bf96b2015-02-22 19:32:03 +00004081 unsigned Alignment;
4082 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
4083 return EC;
4084 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00004085 if (Record[6]) {
4086 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004087 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00004088 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00004089 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004090 // Local linkage must have default visibility.
4091 if (!Func->hasLocalLinkage())
4092 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004093 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00004094 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00004095 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004096 return error("Invalid ID");
Benjamin Kramer728f4442016-05-29 10:46:35 +00004097 Func->setGC(GCTable[Record[8] - 1]);
Gordon Henriksen71183b62007-12-10 03:18:06 +00004098 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004099 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00004100 if (Record.size() > 9)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004101 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00004102 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00004103 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004104 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00004105
4106 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004107 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00004108 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004109 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00004110
Rafael Espindola12ca34f2015-01-19 15:16:06 +00004111 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00004112 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00004113 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004114 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00004115 Func->setComdat(ComdatList[ComdatID - 1]);
4116 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00004117 } else if (hasImplicitComdat(RawLinkage)) {
4118 Func->setComdat(reinterpret_cast<Comdat *>(1));
4119 }
David Majnemerdad0a642014-06-27 18:19:56 +00004120
Peter Collingbourne51d2de72014-12-03 02:08:38 +00004121 if (Record.size() > 13 && Record[13] != 0)
4122 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
4123
David Majnemer7fddecc2015-06-17 20:52:32 +00004124 if (Record.size() > 14 && Record[14] != 0)
4125 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
4126
Chris Lattnerccaa4482007-04-23 21:26:05 +00004127 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004128
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004129 // If this is a function with a body, remember the prototype we are
4130 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004131 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004132 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004133 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004134 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004135 }
Chris Lattner1314b992007-04-22 06:23:29 +00004136 break;
4137 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00004138 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
4139 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
Dmitry Polukhina1feff72016-04-07 12:32:19 +00004140 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
4141 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00004142 case bitc::MODULE_CODE_ALIAS:
4143 case bitc::MODULE_CODE_ALIAS_OLD: {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00004144 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00004145 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004146 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00004147 unsigned OpNum = 0;
4148 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004149 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004150 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004151
David Blaikie6a51dbd2015-09-17 22:18:59 +00004152 unsigned AddrSpace;
4153 if (!NewRecord) {
4154 auto *PTy = dyn_cast<PointerType>(Ty);
4155 if (!PTy)
4156 return error("Invalid type for value");
4157 Ty = PTy->getElementType();
4158 AddrSpace = PTy->getAddressSpace();
4159 } else {
4160 AddrSpace = Record[OpNum++];
4161 }
4162
4163 auto Val = Record[OpNum++];
4164 auto Linkage = Record[OpNum++];
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00004165 GlobalIndirectSymbol *NewGA;
4166 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4167 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Dmitry Polukhina1feff72016-04-07 12:32:19 +00004168 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
4169 "", TheModule);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00004170 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00004171 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
4172 "", nullptr, TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00004173 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00004174 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00004175 if (OpNum != Record.size()) {
4176 auto VisInd = OpNum++;
4177 if (!NewGA->hasLocalLinkage())
4178 // FIXME: Change to an error if non-default in 4.0.
4179 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4180 }
4181 if (OpNum != Record.size())
4182 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00004183 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00004184 upgradeDLLImportExportLinkage(NewGA, Linkage);
4185 if (OpNum != Record.size())
4186 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4187 if (OpNum != Record.size())
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004188 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
Chris Lattner44c17072007-04-26 02:46:40 +00004189 ValueList.push_back(NewGA);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00004190 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00004191 break;
Chris Lattner1314b992007-04-22 06:23:29 +00004192 }
Chris Lattner831d4202007-04-26 03:27:58 +00004193 /// MODULE_CODE_PURGEVALS: [numvals]
4194 case bitc::MODULE_CODE_PURGEVALS:
4195 // Trim down the value list to the specified size.
4196 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004197 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00004198 ValueList.shrinkTo(Record[0]);
4199 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00004200 /// MODULE_CODE_VSTOFFSET: [offset]
4201 case bitc::MODULE_CODE_VSTOFFSET:
4202 if (Record.size() < 1)
4203 return error("Invalid record");
4204 VSTOffset = Record[0];
4205 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004206 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4207 case bitc::MODULE_CODE_SOURCE_FILENAME:
4208 SmallString<128> ValueName;
4209 if (convertToString(Record, 0, ValueName))
4210 return error("Invalid record");
4211 TheModule->setSourceFileName(ValueName);
4212 break;
Chris Lattner831d4202007-04-26 03:27:58 +00004213 }
Chris Lattner1314b992007-04-22 06:23:29 +00004214 Record.clear();
4215 }
Chris Lattner1314b992007-04-22 06:23:29 +00004216}
4217
Teresa Johnson403a7872015-10-04 14:33:43 +00004218/// Helper to read the header common to all bitcode files.
4219static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
4220 // Sniff for the signature.
Peter Collingbourneff2c2ec2016-11-02 00:39:11 +00004221 if (!Stream.canSkipToPos(4) ||
4222 Stream.Read(8) != 'B' ||
Teresa Johnson403a7872015-10-04 14:33:43 +00004223 Stream.Read(8) != 'C' ||
4224 Stream.Read(4) != 0x0 ||
4225 Stream.Read(4) != 0xC ||
4226 Stream.Read(4) != 0xE ||
4227 Stream.Read(4) != 0xD)
4228 return false;
4229 return true;
4230}
4231
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004232std::error_code BitcodeReader::parseBitcodeInto(Module *M,
4233 bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004234 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004235
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004236 if (std::error_code EC = initStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004237 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004238
Chris Lattner1314b992007-04-22 06:23:29 +00004239 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004240 if (!hasValidBitcodeHeader(Stream))
4241 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004242
Chris Lattner1314b992007-04-22 06:23:29 +00004243 // We expect a number of well-defined blocks, though we don't necessarily
4244 // need to understand them all.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004245 while (true) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004246 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004247 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004248 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004249 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004250
Chris Lattner27d38752013-01-20 02:13:19 +00004251 BitstreamEntry Entry =
4252 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00004253
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004254 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004255 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00004256
Mehdi Amini5d303282015-10-26 18:37:00 +00004257 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4258 parseBitcodeVersion();
4259 continue;
4260 }
4261
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004262 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00004263 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00004264
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004265 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004266 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00004267 }
Chris Lattner1314b992007-04-22 06:23:29 +00004268}
Chris Lattner6694f602007-04-29 07:54:31 +00004269
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004270ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00004271 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004272 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00004273
4274 SmallVector<uint64_t, 64> Record;
4275
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004276 std::string Triple;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004277
Bill Wendling0198ce02010-10-06 01:22:42 +00004278 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004279 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00004280 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004281
Chris Lattner27d38752013-01-20 02:13:19 +00004282 switch (Entry.Kind) {
4283 case BitstreamEntry::SubBlock: // Handled for us already.
4284 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004285 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004286 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00004287 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00004288 case BitstreamEntry::Record:
4289 // The interesting case.
4290 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00004291 }
4292
4293 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00004294 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00004295 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00004296 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004297 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004298 if (convertToString(Record, 0, S))
4299 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004300 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00004301 break;
4302 }
4303 }
4304 Record.clear();
4305 }
Rafael Espindolae6107792014-07-04 20:05:56 +00004306 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00004307}
4308
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004309ErrorOr<std::string> BitcodeReader::parseTriple() {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004310 if (std::error_code EC = initStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004311 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00004312
4313 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004314 if (!hasValidBitcodeHeader(Stream))
4315 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00004316
4317 // We expect a number of well-defined blocks, though we don't necessarily
4318 // need to understand them all.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004319 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00004320 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004321
Chris Lattner27d38752013-01-20 02:13:19 +00004322 switch (Entry.Kind) {
4323 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004324 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004325 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004326 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00004327
Chris Lattner27d38752013-01-20 02:13:19 +00004328 case BitstreamEntry::SubBlock:
4329 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00004330 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00004331
Chris Lattner27d38752013-01-20 02:13:19 +00004332 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00004333 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004334 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004335 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004336
Chris Lattner27d38752013-01-20 02:13:19 +00004337 case BitstreamEntry::Record:
4338 Stream.skipRecord(Entry.ID);
4339 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00004340 }
4341 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004342}
4343
Mehdi Amini3383ccc2015-11-09 02:46:41 +00004344ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004345 if (std::error_code EC = initStream())
Mehdi Amini3383ccc2015-11-09 02:46:41 +00004346 return EC;
4347
4348 // Sniff for the signature.
4349 if (!hasValidBitcodeHeader(Stream))
4350 return error("Invalid bitcode signature");
4351
4352 // We expect a number of well-defined blocks, though we don't necessarily
4353 // need to understand them all.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004354 while (true) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00004355 BitstreamEntry Entry = Stream.advance();
4356 switch (Entry.Kind) {
4357 case BitstreamEntry::Error:
4358 return error("Malformed block");
4359 case BitstreamEntry::EndBlock:
4360 return std::error_code();
4361
4362 case BitstreamEntry::SubBlock:
4363 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4364 if (std::error_code EC = parseBitcodeVersion())
4365 return EC;
4366 return ProducerIdentification;
4367 }
4368 // Ignore other sub-blocks.
4369 if (Stream.SkipBlock())
4370 return error("Malformed block");
4371 continue;
4372 case BitstreamEntry::Record:
4373 Stream.skipRecord(Entry.ID);
4374 continue;
4375 }
4376 }
4377}
4378
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004379std::error_code BitcodeReader::parseGlobalObjectAttachment(
4380 GlobalObject &GO, ArrayRef<uint64_t> Record) {
4381 assert(Record.size() % 2 == 0);
4382 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
4383 auto K = MDKindMap.find(Record[I]);
4384 if (K == MDKindMap.end())
4385 return error("Invalid ID");
4386 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4387 if (!MD)
4388 return error("Invalid metadata attachment");
Peter Collingbourne382d81c2016-06-01 01:17:57 +00004389 GO.addMetadata(K->second, *MD);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004390 }
4391 return std::error_code();
4392}
4393
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00004394ErrorOr<bool> BitcodeReader::hasObjCCategory() {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004395 if (std::error_code EC = initStream())
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00004396 return EC;
4397
4398 // Sniff for the signature.
4399 if (!hasValidBitcodeHeader(Stream))
4400 return error("Invalid bitcode signature");
4401
4402 // We expect a number of well-defined blocks, though we don't necessarily
4403 // need to understand them all.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004404 while (true) {
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00004405 BitstreamEntry Entry = Stream.advance();
4406
4407 switch (Entry.Kind) {
4408 case BitstreamEntry::Error:
4409 return error("Malformed block");
4410 case BitstreamEntry::EndBlock:
4411 return std::error_code();
4412
4413 case BitstreamEntry::SubBlock:
4414 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4415 return hasObjCCategoryInModule();
4416
4417 // Ignore other sub-blocks.
4418 if (Stream.SkipBlock())
4419 return error("Malformed block");
4420 continue;
4421
4422 case BitstreamEntry::Record:
4423 Stream.skipRecord(Entry.ID);
4424 continue;
4425 }
4426 }
4427}
4428
4429ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() {
4430 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4431 return error("Invalid record");
4432
4433 SmallVector<uint64_t, 64> Record;
4434 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004435
4436 while (true) {
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00004437 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4438
4439 switch (Entry.Kind) {
4440 case BitstreamEntry::SubBlock: // Handled for us already.
4441 case BitstreamEntry::Error:
4442 return error("Malformed block");
4443 case BitstreamEntry::EndBlock:
4444 return false;
4445 case BitstreamEntry::Record:
4446 // The interesting case.
4447 break;
4448 }
4449
4450 // Read a record.
4451 switch (Stream.readRecord(Entry.ID, Record)) {
4452 default:
4453 break; // Default behavior, ignore unknown content.
4454 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4455 std::string S;
4456 if (convertToString(Record, 0, S))
4457 return error("Invalid record");
4458 // Check for the i386 and other (x86_64, ARM) conventions
4459 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
4460 S.find("__OBJC,__category") != std::string::npos)
4461 return true;
4462 break;
4463 }
4464 }
4465 Record.clear();
4466 }
4467 llvm_unreachable("Exit infinite loop");
4468}
4469
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004470/// Parse metadata attachments.
4471std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00004472 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004473 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004474
Devang Patelaf206b82009-09-18 19:26:43 +00004475 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004476
4477 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00004478 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004479
Chris Lattner27d38752013-01-20 02:13:19 +00004480 switch (Entry.Kind) {
4481 case BitstreamEntry::SubBlock: // Handled for us already.
4482 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004483 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004484 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004485 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00004486 case BitstreamEntry::Record:
4487 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00004488 break;
4489 }
Chris Lattner27d38752013-01-20 02:13:19 +00004490
Devang Patelaf206b82009-09-18 19:26:43 +00004491 // Read a metadata attachment record.
4492 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00004493 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00004494 default: // Default behavior: ignore.
4495 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00004496 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00004497 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004498 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004499 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004500 if (RecordLength % 2 == 0) {
4501 // A function attachment.
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004502 if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
4503 return EC;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004504 continue;
4505 }
4506
4507 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00004508 Instruction *Inst = InstructionList[Record[0]];
4509 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00004510 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00004511 DenseMap<unsigned, unsigned>::iterator I =
4512 MDKindMap.find(Kind);
4513 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004514 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00004515 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004516 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00004517 // Drop the attachment. This used to be legal, but there's no
4518 // upgrade path.
4519 break;
Justin Bognerae341c62016-03-17 20:12:06 +00004520 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4521 if (!MD)
4522 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004523
4524 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4525 MD = upgradeInstructionLoopAttachment(*MD);
4526
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004527 if (I->second == LLVMContext::MD_tbaa) {
Mehdi Aminie4709272016-09-14 22:29:59 +00004528 assert(!MD->isTemporary() && "should load MDs before attachments");
4529 MD = UpgradeTBAANode(*MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004530 }
Mehdi Aminie4709272016-09-14 22:29:59 +00004531 Inst->setMetadata(I->second, MD);
Devang Patelaf206b82009-09-18 19:26:43 +00004532 }
4533 break;
4534 }
4535 }
4536 }
Devang Patelaf206b82009-09-18 19:26:43 +00004537}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004538
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004539static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4540 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004541 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004542 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004543 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4544
4545 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004546 return error(Context, "Explicit load/store type does not match pointee "
4547 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004548 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004549 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004550 return std::error_code();
4551}
4552
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004553/// Lazily parse the specified function body block.
4554std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00004555 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004556 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004557
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004558 // Unexpected unresolved metadata when parsing function.
4559 if (MetadataList.hasFwdRefs())
4560 return error("Invalid function metadata: incoming forward references");
4561
Nick Lewyckya72e1af2010-02-25 08:30:17 +00004562 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00004563 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00004564 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004565
Chris Lattner85b7b402007-05-01 05:52:21 +00004566 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004567 for (Argument &I : F->args())
4568 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004569
Chris Lattner83930552007-05-01 07:01:57 +00004570 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00004571 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00004572 unsigned CurBBNo = 0;
4573
Chris Lattner07d09ed2010-04-03 02:17:50 +00004574 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004575 auto getLastInstruction = [&]() -> Instruction * {
4576 if (CurBB && !CurBB->empty())
4577 return &CurBB->back();
4578 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4579 !FunctionBBs[CurBBNo - 1]->empty())
4580 return &FunctionBBs[CurBBNo - 1]->back();
4581 return nullptr;
4582 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004583
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004584 std::vector<OperandBundleDef> OperandBundles;
4585
Chris Lattner85b7b402007-05-01 05:52:21 +00004586 // Read all the records.
4587 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004588
4589 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00004590 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004591
Chris Lattner27d38752013-01-20 02:13:19 +00004592 switch (Entry.Kind) {
4593 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004594 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004595 case BitstreamEntry::EndBlock:
4596 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004597
Chris Lattner27d38752013-01-20 02:13:19 +00004598 case BitstreamEntry::SubBlock:
4599 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004600 default: // Skip unknown content.
4601 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004602 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004603 break;
4604 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004605 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004606 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004607 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004608 break;
4609 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004610 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004611 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004612 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004613 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004614 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004615 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004616 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004617 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004618 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004619 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004620 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004621 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004622 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004623 return EC;
4624 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004625 }
4626 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004627
Chris Lattner27d38752013-01-20 02:13:19 +00004628 case BitstreamEntry::Record:
4629 // The interesting case.
4630 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004631 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004632
Chris Lattner85b7b402007-05-01 05:52:21 +00004633 // Read a record.
4634 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004635 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004636 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004637 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004638 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004639 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004640 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004641 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004642 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004643 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004644 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004645
4646 // See if anything took the address of blocks in this function.
4647 auto BBFRI = BasicBlockFwdRefs.find(F);
4648 if (BBFRI == BasicBlockFwdRefs.end()) {
4649 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4650 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4651 } else {
4652 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004653 // Check for invalid basic block references.
4654 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004655 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004656 assert(!BBRefs.empty() && "Unexpected empty array");
4657 assert(!BBRefs.front() && "Invalid reference to entry block");
4658 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4659 ++I)
4660 if (I < RE && BBRefs[I]) {
4661 BBRefs[I]->insertInto(F);
4662 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004663 } else {
4664 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4665 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004666
4667 // Erase from the table.
4668 BasicBlockFwdRefs.erase(BBFRI);
4669 }
4670
Chris Lattner83930552007-05-01 07:01:57 +00004671 CurBB = FunctionBBs[0];
4672 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004673 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004674
Chris Lattner07d09ed2010-04-03 02:17:50 +00004675 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4676 // This record indicates that the last instruction is at the same
4677 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004678 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004679
Craig Topper2617dcc2014-04-15 06:32:26 +00004680 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004681 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004682 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004683 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004684 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004685
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004686 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004687 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004688 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004689 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004690
Chris Lattner07d09ed2010-04-03 02:17:50 +00004691 unsigned Line = Record[0], Col = Record[1];
4692 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004693
Craig Topper2617dcc2014-04-15 06:32:26 +00004694 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004695 if (ScopeID) {
4696 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4697 if (!Scope)
4698 return error("Invalid record");
4699 }
4700 if (IAID) {
4701 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4702 if (!IA)
4703 return error("Invalid record");
4704 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004705 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4706 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004707 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004708 continue;
4709 }
4710
Chris Lattnere9759c22007-05-06 00:21:25 +00004711 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4712 unsigned OpNum = 0;
4713 Value *LHS, *RHS;
4714 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004715 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004716 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004717 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004718
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004719 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004720 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004721 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004722 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004723 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004724 if (OpNum < Record.size()) {
4725 if (Opc == Instruction::Add ||
4726 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004727 Opc == Instruction::Mul ||
4728 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004729 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004730 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004731 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004732 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004733 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004734 Opc == Instruction::UDiv ||
4735 Opc == Instruction::LShr ||
4736 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004737 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004738 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004739 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004740 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004741 if (FMF.any())
4742 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004743 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004744
Dan Gohman1b849082009-09-07 23:54:19 +00004745 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004746 break;
4747 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004748 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4749 unsigned OpNum = 0;
4750 Value *Op;
4751 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4752 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004753 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754
Chris Lattner229907c2011-07-18 04:54:35 +00004755 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004756 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004757 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004758 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004759 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004760 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4761 if (Temp) {
4762 InstructionList.push_back(Temp);
4763 CurBB->getInstList().push_back(Temp);
4764 }
4765 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004766 auto CastOp = (Instruction::CastOps)Opc;
4767 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4768 return error("Invalid cast");
4769 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004770 }
Devang Patelaf206b82009-09-18 19:26:43 +00004771 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004772 break;
4773 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004774 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4775 case bitc::FUNC_CODE_INST_GEP_OLD:
4776 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004777 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004778
4779 Type *Ty;
4780 bool InBounds;
4781
4782 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4783 InBounds = Record[OpNum++];
4784 Ty = getTypeByID(Record[OpNum++]);
4785 } else {
4786 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4787 Ty = nullptr;
4788 }
4789
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004790 Value *BasePtr;
4791 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004792 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004793
David Blaikie60310f22015-05-08 00:42:26 +00004794 if (!Ty)
4795 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4796 ->getElementType();
4797 else if (Ty !=
4798 cast<SequentialType>(BasePtr->getType()->getScalarType())
4799 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004800 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004801 "Explicit gep type does not match pointee type of pointer operand");
4802
Chris Lattner5285b5e2007-05-02 05:46:45 +00004803 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004804 while (OpNum != Record.size()) {
4805 Value *Op;
4806 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004807 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004808 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004809 }
4810
David Blaikie096b1da2015-03-14 19:53:33 +00004811 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004812
Devang Patelaf206b82009-09-18 19:26:43 +00004813 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004814 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004815 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004816 break;
4817 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004818
Dan Gohman1ecaf452008-05-31 00:58:22 +00004819 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4820 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004821 unsigned OpNum = 0;
4822 Value *Agg;
4823 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004824 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004825
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004826 unsigned RecSize = Record.size();
4827 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004828 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004829
Dan Gohman1ecaf452008-05-31 00:58:22 +00004830 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004831 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004832 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004833 bool IsArray = CurTy->isArrayTy();
4834 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004835 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004836
4837 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004838 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004839 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004840 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004841 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004842 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004843 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004844 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004845 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004846
4847 if (IsStruct)
4848 CurTy = CurTy->subtypes()[Index];
4849 else
4850 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004851 }
4852
Jay Foad57aa6362011-07-13 10:26:04 +00004853 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004854 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004855 break;
4856 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004857
Dan Gohman1ecaf452008-05-31 00:58:22 +00004858 case bitc::FUNC_CODE_INST_INSERTVAL: {
4859 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004860 unsigned OpNum = 0;
4861 Value *Agg;
4862 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004863 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004864 Value *Val;
4865 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004866 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004867
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004868 unsigned RecSize = Record.size();
4869 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004870 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004871
Dan Gohman1ecaf452008-05-31 00:58:22 +00004872 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004873 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004874 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004875 bool IsArray = CurTy->isArrayTy();
4876 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004877 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004878
4879 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004880 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004881 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004882 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004883 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004884 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004885 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004886 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004887
Dan Gohman1ecaf452008-05-31 00:58:22 +00004888 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004889 if (IsStruct)
4890 CurTy = CurTy->subtypes()[Index];
4891 else
4892 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004893 }
4894
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004895 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004896 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004897
Jay Foad57aa6362011-07-13 10:26:04 +00004898 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004899 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004900 break;
4901 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004902
Chris Lattnere9759c22007-05-06 00:21:25 +00004903 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004904 // obsolete form of select
4905 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004906 unsigned OpNum = 0;
4907 Value *TrueVal, *FalseVal, *Cond;
4908 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004909 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4910 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004911 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004912
Dan Gohmanc5d28922008-09-16 01:01:33 +00004913 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004914 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004915 break;
4916 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004917
Dan Gohmanc5d28922008-09-16 01:01:33 +00004918 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4919 // new form of select
4920 // handles select i1 or select [N x i1]
4921 unsigned OpNum = 0;
4922 Value *TrueVal, *FalseVal, *Cond;
4923 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004924 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004925 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004926 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004927
4928 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004929 if (VectorType* vector_type =
4930 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004931 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004932 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004933 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004934 } else {
4935 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004936 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004937 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004938 }
4939
Gabor Greife9ecc682008-04-06 20:25:17 +00004940 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004941 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004942 break;
4943 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004944
Chris Lattner1fc27f02007-05-02 05:16:49 +00004945 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004946 unsigned OpNum = 0;
4947 Value *Vec, *Idx;
4948 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004949 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004950 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004951 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004952 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004953 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004954 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004955 break;
4956 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004957
Chris Lattner1fc27f02007-05-02 05:16:49 +00004958 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004959 unsigned OpNum = 0;
4960 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004961 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004962 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004963 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004964 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004965 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004966 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004967 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004968 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004969 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004970 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004971 break;
4972 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004973
Chris Lattnere9759c22007-05-06 00:21:25 +00004974 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4975 unsigned OpNum = 0;
4976 Value *Vec1, *Vec2, *Mask;
4977 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004978 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004979 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004980
Mon P Wang25f01062008-11-10 04:46:22 +00004981 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004982 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004983 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004984 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004985 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004986 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004987 break;
4988 }
Mon P Wang25f01062008-11-10 04:46:22 +00004989
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004990 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4991 // Old form of ICmp/FCmp returning bool
4992 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4993 // both legal on vectors but had different behaviour.
4994 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4995 // FCmp/ICmp returning bool or vector of bool
4996
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004997 unsigned OpNum = 0;
4998 Value *LHS, *RHS;
4999 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00005000 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
5001 return error("Invalid record");
5002
5003 unsigned PredVal = Record[OpNum];
5004 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5005 FastMathFlags FMF;
5006 if (IsFP && Record.size() > OpNum+1)
5007 FMF = getDecodedFastMathFlags(Record[++OpNum]);
5008
5009 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005010 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005011
Duncan Sands9dff9be2010-02-15 16:12:20 +00005012 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00005013 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005014 else
James Molloy88eb5352015-07-10 12:52:00 +00005015 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
5016
5017 if (FMF.any())
5018 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00005019 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00005020 break;
5021 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00005022
Chris Lattnere53603e2007-05-02 04:27:25 +00005023 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00005024 {
5025 unsigned Size = Record.size();
5026 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00005027 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005028 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00005029 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00005030 }
Devang Patelbbfd8742008-02-26 01:29:32 +00005031
Dan Gohmanfa1211f2008-07-23 00:34:11 +00005032 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005033 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00005034 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005035 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00005036 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005037 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00005038
Chris Lattnerf1c87102011-06-17 18:09:11 +00005039 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005040 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00005041 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00005042 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00005043 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00005044 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005045 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005046 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00005047 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005048 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005049
Devang Patelaf206b82009-09-18 19:26:43 +00005050 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00005051 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005052 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00005053 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00005054 else {
5055 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005056 Value *Cond = getValue(Record, 2, NextValueNo,
5057 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00005058 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005059 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00005060 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005061 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00005062 }
5063 break;
5064 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00005065 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005066 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00005067 return error("Invalid record");
5068 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005069 Value *CleanupPad =
5070 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005071 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00005072 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005073 BasicBlock *UnwindDest = nullptr;
5074 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00005075 UnwindDest = getBasicBlock(Record[Idx++]);
5076 if (!UnwindDest)
5077 return error("Invalid record");
5078 }
5079
David Majnemer8a1c45d2015-12-12 05:38:55 +00005080 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00005081 InstructionList.push_back(I);
5082 break;
5083 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005084 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5085 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00005086 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00005087 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005088 Value *CatchPad =
5089 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005090 if (!CatchPad)
5091 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00005092 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00005093 if (!BB)
5094 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00005095
David Majnemer8a1c45d2015-12-12 05:38:55 +00005096 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00005097 InstructionList.push_back(I);
5098 break;
5099 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00005100 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5101 // We must have, at minimum, the outer scope and the number of arguments.
5102 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00005103 return error("Invalid record");
5104
David Majnemer654e1302015-07-31 17:58:14 +00005105 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005106
5107 Value *ParentPad =
5108 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
5109
5110 unsigned NumHandlers = Record[Idx++];
5111
5112 SmallVector<BasicBlock *, 2> Handlers;
5113 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5114 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5115 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00005116 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00005117 Handlers.push_back(BB);
5118 }
5119
5120 BasicBlock *UnwindDest = nullptr;
5121 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00005122 UnwindDest = getBasicBlock(Record[Idx++]);
5123 if (!UnwindDest)
5124 return error("Invalid record");
5125 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00005126
5127 if (Record.size() != Idx)
5128 return error("Invalid record");
5129
5130 auto *CatchSwitch =
5131 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5132 for (BasicBlock *Handler : Handlers)
5133 CatchSwitch->addHandler(Handler);
5134 I = CatchSwitch;
5135 InstructionList.push_back(I);
5136 break;
5137 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00005138 case bitc::FUNC_CODE_INST_CATCHPAD:
5139 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5140 // We must have, at minimum, the outer scope and the number of arguments.
5141 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00005142 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00005143
David Majnemer654e1302015-07-31 17:58:14 +00005144 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00005145
5146 Value *ParentPad =
5147 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
5148
David Majnemer654e1302015-07-31 17:58:14 +00005149 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00005150
David Majnemer654e1302015-07-31 17:58:14 +00005151 SmallVector<Value *, 2> Args;
5152 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5153 Value *Val;
5154 if (getValueTypePair(Record, Idx, NextValueNo, Val))
5155 return error("Invalid record");
5156 Args.push_back(Val);
5157 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00005158
David Majnemer654e1302015-07-31 17:58:14 +00005159 if (Record.size() != Idx)
5160 return error("Invalid record");
5161
David Majnemer8a1c45d2015-12-12 05:38:55 +00005162 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5163 I = CleanupPadInst::Create(ParentPad, Args);
5164 else
5165 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00005166 InstructionList.push_back(I);
5167 break;
5168 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00005169 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005170 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005171 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00005172 // "New" SwitchInst format with case ranges. The changes to write this
5173 // format were reverted but we still recognize bitcode that uses it.
5174 // Hopefully someday we will have support for case ranges and can use
5175 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005176
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005177 Type *OpTy = getTypeByID(Record[1]);
5178 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5179
Jan Wen Voungafaced02012-10-11 20:20:40 +00005180 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005181 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00005182 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005183 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005184
5185 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005186
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005187 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5188 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005189
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005190 unsigned CurIdx = 5;
5191 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00005192 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005193 unsigned NumItems = Record[CurIdx++];
5194 for (unsigned ci = 0; ci != NumItems; ++ci) {
5195 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005196
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005197 APInt Low;
5198 unsigned ActiveWords = 1;
5199 if (ValueBitWidth > 64)
5200 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005201 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00005202 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005203 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00005204
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005205 if (!isSingleNumber) {
5206 ActiveWords = 1;
5207 if (ValueBitWidth > 64)
5208 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005209 APInt High = readWideAPInt(
5210 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005211 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00005212
5213 // FIXME: It is not clear whether values in the range should be
5214 // compared as signed or unsigned values. The partially
5215 // implemented changes that used this format in the past used
5216 // unsigned comparisons.
5217 for ( ; Low.ule(High); ++Low)
5218 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005219 } else
Bob Wilsone4077362013-09-09 19:14:35 +00005220 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005221 }
5222 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00005223 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
5224 cve = CaseVals.end(); cvi != cve; ++cvi)
5225 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005226 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005227 I = SI;
5228 break;
5229 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005230
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00005231 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005232
Chris Lattner5285b5e2007-05-02 05:46:45 +00005233 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005234 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005235 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005236 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00005237 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00005238 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005239 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005240 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00005241 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00005242 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00005243 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005244 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00005245 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
5246 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00005247 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00005248 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005249 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005250 }
5251 SI->addCase(CaseVal, DestBB);
5252 }
5253 I = SI;
5254 break;
5255 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005256 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00005257 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005258 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005259 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005260 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00005261 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005262 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00005263 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00005264 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00005265 InstructionList.push_back(IBI);
5266 for (unsigned i = 0, e = NumDests; i != e; ++i) {
5267 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5268 IBI->addDestination(DestBB);
5269 } else {
5270 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005271 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00005272 }
5273 }
5274 I = IBI;
5275 break;
5276 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005277
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005278 case bitc::FUNC_CODE_INST_INVOKE: {
5279 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00005280 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005281 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005282 unsigned OpNum = 0;
5283 AttributeSet PAL = getAttributes(Record[OpNum++]);
5284 unsigned CCInfo = Record[OpNum++];
5285 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5286 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005287
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005288 FunctionType *FTy = nullptr;
5289 if (CCInfo >> 13 & 1 &&
5290 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005291 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005292
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005293 Value *Callee;
5294 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005295 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005296
Chris Lattner229907c2011-07-18 04:54:35 +00005297 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005298 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005299 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005300 if (!FTy) {
5301 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5302 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005303 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005304 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005305 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005306 "callee operand");
5307 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005308 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005309
Chris Lattner5285b5e2007-05-02 05:46:45 +00005310 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005311 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005312 Ops.push_back(getValue(Record, OpNum, NextValueNo,
5313 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005314 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005315 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005316 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005317
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005318 if (!FTy->isVarArg()) {
5319 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005320 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005321 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005322 // Read type/value pairs for varargs params.
5323 while (OpNum != Record.size()) {
5324 Value *Op;
5325 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005326 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005327 Ops.push_back(Op);
5328 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00005329 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005330
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005331 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
5332 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005333 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00005334 cast<InvokeInst>(I)->setCallingConv(
5335 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00005336 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00005337 break;
5338 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00005339 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5340 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005341 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005342 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005343 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00005344 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00005345 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005346 break;
5347 }
Chris Lattnere53603e2007-05-02 04:27:25 +00005348 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00005349 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00005350 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00005351 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00005352 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00005353 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005354 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005355 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005356 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005357 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005358
Jay Foad52131342011-03-30 11:28:46 +00005359 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00005360 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005361
Chris Lattnere14cb882007-05-04 19:11:41 +00005362 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005363 Value *V;
5364 // With the new function encoding, it is possible that operands have
5365 // negative IDs (for forward references). Use a signed VBR
5366 // representation to keep the encoding small.
5367 if (UseRelativeIDs)
5368 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5369 else
5370 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00005371 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005372 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005373 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00005374 PN->addIncoming(V, BB);
5375 }
5376 I = PN;
5377 break;
5378 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005379
David Majnemer7fddecc2015-06-17 20:52:32 +00005380 case bitc::FUNC_CODE_INST_LANDINGPAD:
5381 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00005382 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5383 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00005384 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5385 if (Record.size() < 3)
5386 return error("Invalid record");
5387 } else {
5388 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5389 if (Record.size() < 4)
5390 return error("Invalid record");
5391 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005392 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005393 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005394 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00005395 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5396 Value *PersFn = nullptr;
5397 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5398 return error("Invalid record");
5399
5400 if (!F->hasPersonalityFn())
5401 F->setPersonalityFn(cast<Constant>(PersFn));
5402 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5403 return error("Personality function mismatch");
5404 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005405
5406 bool IsCleanup = !!Record[Idx++];
5407 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00005408 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00005409 LP->setCleanup(IsCleanup);
5410 for (unsigned J = 0; J != NumClauses; ++J) {
5411 LandingPadInst::ClauseType CT =
5412 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5413 Value *Val;
5414
5415 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5416 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005417 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00005418 }
5419
5420 assert((CT != LandingPadInst::Catch ||
5421 !isa<ArrayType>(Val->getType())) &&
5422 "Catch clause has a invalid type!");
5423 assert((CT != LandingPadInst::Filter ||
5424 isa<ArrayType>(Val->getType())) &&
5425 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005426 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00005427 }
5428
5429 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00005430 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00005431 break;
5432 }
5433
Chris Lattnerf1c87102011-06-17 18:09:11 +00005434 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5435 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005436 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00005437 uint64_t AlignRecord = Record[3];
5438 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00005439 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005440 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5441 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5442 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00005443 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005444 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00005445 Type *Ty = getTypeByID(Record[0]);
5446 if ((AlignRecord & ExplicitTypeMask) == 0) {
5447 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5448 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005449 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00005450 Ty = PTy->getElementType();
5451 }
5452 Type *OpTy = getTypeByID(Record[1]);
5453 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00005454 unsigned Align;
5455 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00005456 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00005457 return EC;
5458 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00005459 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005460 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00005461 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005462 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005463 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005464 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00005465 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00005466 break;
5467 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005468 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005469 unsigned OpNum = 0;
5470 Value *Op;
5471 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005472 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005473 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00005474
5475 Type *Ty = nullptr;
5476 if (OpNum + 3 == Record.size())
5477 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005478 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005479 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005480 if (!Ty)
5481 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005482
JF Bastien30bf96b2015-02-22 19:32:03 +00005483 unsigned Align;
5484 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5485 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005486 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00005487
Devang Patelaf206b82009-09-18 19:26:43 +00005488 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00005489 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00005490 }
Eli Friedman59b66882011-08-09 23:02:53 +00005491 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5492 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5493 unsigned OpNum = 0;
5494 Value *Op;
5495 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005496 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005497 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005498
David Blaikie85035652015-02-25 01:07:20 +00005499 Type *Ty = nullptr;
5500 if (OpNum + 5 == Record.size())
5501 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005502 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005503 return EC;
5504 if (!Ty)
5505 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005506
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005507 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005508 if (Ordering == AtomicOrdering::NotAtomic ||
5509 Ordering == AtomicOrdering::Release ||
5510 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005511 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00005512 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005513 return error("Invalid record");
5514 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00005515
JF Bastien30bf96b2015-02-22 19:32:03 +00005516 unsigned Align;
5517 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5518 return EC;
5519 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00005520
Eli Friedman59b66882011-08-09 23:02:53 +00005521 InstructionList.push_back(I);
5522 break;
5523 }
David Blaikie612ddbf2015-04-22 04:14:42 +00005524 case bitc::FUNC_CODE_INST_STORE:
5525 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005526 unsigned OpNum = 0;
5527 Value *Val, *Ptr;
5528 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00005529 (BitCode == bitc::FUNC_CODE_INST_STORE
5530 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5531 : popValue(Record, OpNum, NextValueNo,
5532 cast<PointerType>(Ptr->getType())->getElementType(),
5533 Val)) ||
5534 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005535 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005536
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005537 if (std::error_code EC =
5538 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005539 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00005540 unsigned Align;
5541 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5542 return EC;
5543 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00005544 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005545 break;
5546 }
David Blaikie50a06152015-04-22 04:14:46 +00005547 case bitc::FUNC_CODE_INST_STOREATOMIC:
5548 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00005549 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5550 unsigned OpNum = 0;
5551 Value *Val, *Ptr;
5552 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00005553 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00005554 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5555 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5556 : popValue(Record, OpNum, NextValueNo,
5557 cast<PointerType>(Ptr->getType())->getElementType(),
5558 Val)) ||
5559 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005560 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005561
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005562 if (std::error_code EC =
5563 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005564 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005565 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005566 if (Ordering == AtomicOrdering::NotAtomic ||
5567 Ordering == AtomicOrdering::Acquire ||
5568 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005569 return error("Invalid record");
5570 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00005571 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005572 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005573
JF Bastien30bf96b2015-02-22 19:32:03 +00005574 unsigned Align;
5575 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5576 return EC;
5577 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00005578 InstructionList.push_back(I);
5579 break;
5580 }
David Blaikie2a661cd2015-04-28 04:30:29 +00005581 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005582 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00005583 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00005584 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005585 unsigned OpNum = 0;
5586 Value *Ptr, *Cmp, *New;
5587 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005588 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5589 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5590 : popValue(Record, OpNum, NextValueNo,
5591 cast<PointerType>(Ptr->getType())->getElementType(),
5592 Cmp)) ||
5593 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5594 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005595 return error("Invalid record");
5596 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00005597 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5598 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005599 return error("Invalid record");
5600 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005601
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005602 if (std::error_code EC =
5603 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005604 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005605 AtomicOrdering FailureOrdering;
5606 if (Record.size() < 7)
5607 FailureOrdering =
5608 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5609 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005610 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005611
5612 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5613 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005614 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005615
5616 if (Record.size() < 8) {
5617 // Before weak cmpxchgs existed, the instruction simply returned the
5618 // value loaded from memory, so bitcode files from that era will be
5619 // expecting the first component of a modern cmpxchg.
5620 CurBB->getInstList().push_back(I);
5621 I = ExtractValueInst::Create(I, 0);
5622 } else {
5623 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5624 }
5625
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005626 InstructionList.push_back(I);
5627 break;
5628 }
5629 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5630 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5631 unsigned OpNum = 0;
5632 Value *Ptr, *Val;
5633 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00005634 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005635 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005636 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5637 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005638 return error("Invalid record");
5639 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005640 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5641 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005642 return error("Invalid record");
5643 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005644 if (Ordering == AtomicOrdering::NotAtomic ||
5645 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005646 return error("Invalid record");
5647 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005648 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5649 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5650 InstructionList.push_back(I);
5651 break;
5652 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005653 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5654 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005655 return error("Invalid record");
5656 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00005657 if (Ordering == AtomicOrdering::NotAtomic ||
5658 Ordering == AtomicOrdering::Unordered ||
5659 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005660 return error("Invalid record");
5661 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005662 I = new FenceInst(Context, Ordering, SynchScope);
5663 InstructionList.push_back(I);
5664 break;
5665 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005666 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005667 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005668 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005669 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005670
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005671 unsigned OpNum = 0;
5672 AttributeSet PAL = getAttributes(Record[OpNum++]);
5673 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005674
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005675 FastMathFlags FMF;
5676 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5677 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5678 if (!FMF.any())
5679 return error("Fast math flags indicator set for call with no FMF");
5680 }
5681
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005682 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005683 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005684 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005685 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005686
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005687 Value *Callee;
5688 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005689 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005690
Chris Lattner229907c2011-07-18 04:54:35 +00005691 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005692 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005693 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005694 if (!FTy) {
5695 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5696 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005697 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005698 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005699 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005700 "callee operand");
5701 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005702 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005703
Chris Lattner9f600c52007-05-03 22:04:19 +00005704 SmallVector<Value*, 16> Args;
5705 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005706 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005707 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005708 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005709 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005710 Args.push_back(getValue(Record, OpNum, NextValueNo,
5711 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005712 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005713 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005714 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005715
Chris Lattner9f600c52007-05-03 22:04:19 +00005716 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005717 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005718 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005719 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005720 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005721 while (OpNum != Record.size()) {
5722 Value *Op;
5723 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005724 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005725 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005726 }
5727 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005728
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005729 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5730 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005731 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005732 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005733 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005734 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005735 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005736 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005737 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005738 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005739 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005740 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005741 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005742 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005743 if (FMF.any()) {
5744 if (!isa<FPMathOperator>(I))
5745 return error("Fast-math-flags specified for call without "
5746 "floating-point scalar or vector return type");
5747 I->setFastMathFlags(FMF);
5748 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005749 break;
5750 }
5751 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5752 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005753 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005754 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005755 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005756 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005757 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005758 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005759 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005760 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005761 break;
5762 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005763
5764 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5765 // A call or an invoke can be optionally prefixed with some variable
5766 // number of operand bundle blocks. These blocks are read into
5767 // OperandBundles and consumed at the next call or invoke instruction.
5768
5769 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5770 return error("Invalid record");
5771
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005772 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005773
5774 unsigned OpNum = 1;
5775 while (OpNum != Record.size()) {
5776 Value *Op;
5777 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5778 return error("Invalid record");
5779 Inputs.push_back(Op);
5780 }
5781
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005782 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005783 continue;
5784 }
Chris Lattner83930552007-05-01 07:01:57 +00005785 }
5786
5787 // Add instruction to end of current BB. If there is no current BB, reject
5788 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005789 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005790 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005791 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005792 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005793 if (!OperandBundles.empty()) {
5794 delete I;
5795 return error("Operand bundles found with no consumer");
5796 }
Chris Lattner83930552007-05-01 07:01:57 +00005797 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005798
Chris Lattner83930552007-05-01 07:01:57 +00005799 // If this was a terminator instruction, move to the next block.
5800 if (isa<TerminatorInst>(I)) {
5801 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005802 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005803 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005804
Chris Lattner83930552007-05-01 07:01:57 +00005805 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005806 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005807 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005809
Chris Lattner27d38752013-01-20 02:13:19 +00005810OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005811
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005812 if (!OperandBundles.empty())
5813 return error("Operand bundles found with no consumer");
5814
Chris Lattner83930552007-05-01 07:01:57 +00005815 // Check the function list for unresolved values.
5816 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005817 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005818 // We found at least one unresolved value. Nuke them all to avoid leaks.
5819 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005820 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005821 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005822 delete A;
5823 }
5824 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005825 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005826 }
Chris Lattner83930552007-05-01 07:01:57 +00005827 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005828
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00005829 // Unexpected unresolved metadata about to be dropped.
5830 if (MetadataList.hasFwdRefs())
5831 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00005832
Chris Lattner85b7b402007-05-01 05:52:21 +00005833 // Trim the value list down to the size it was before we parsed this function.
5834 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005835 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005836 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005837 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005838}
5839
Rafael Espindola7d712032013-11-05 17:16:08 +00005840/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005841std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005842 Function *F,
5843 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005844 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005845 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005846 // didn't contain the function index in the VST, or when we have
5847 // an anonymous function which would not have a VST entry.
5848 // Assert that we have one of those two cases.
5849 assert(VSTOffset == 0 || !F->hasName());
5850 // Parse the next body in the stream and set its position in the
5851 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005852 if (std::error_code EC = rememberAndSkipFunctionBodies())
5853 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005854 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005855 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005856}
5857
Chris Lattner9eeada92007-05-18 04:02:46 +00005858//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005859// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005860//===----------------------------------------------------------------------===//
5861
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005862std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005863 Function *F = dyn_cast<Function>(GV);
5864 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005865 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005866 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005867
5868 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005869 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005870 // If its position is recorded as 0, its body is somewhere in the stream
5871 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005872 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005873 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005874 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005875
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00005876 // Materialize metadata before parsing any function bodies.
5877 if (std::error_code EC = materializeMetadata())
5878 return EC;
5879
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005880 // Move the bit stream to the saved position of the deferred function body.
5881 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005882
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005883 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005884 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005885 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005886
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005887 if (StripDebugInfo)
5888 stripDebugInfo(*F);
5889
Chandler Carruth7132e002007-08-04 01:51:18 +00005890 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005891 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005892 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5893 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005894 User *U = *UI;
5895 ++UI;
5896 if (CallInst *CI = dyn_cast<CallInst>(U))
5897 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005898 }
5899 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005900
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00005901 // Update calls to the remangled intrinsics
5902 for (auto &I : RemangledIntrinsics)
5903 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5904 UI != UE;)
5905 // Don't expect any other users than call sites
5906 CallSite(*UI++).setCalledFunction(I.second);
5907
Peter Collingbourned4bff302015-11-05 22:03:56 +00005908 // Finish fn->subprogram upgrade for materialized functions.
5909 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5910 F->setSubprogram(SP);
5911
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005912 // Bring in any functions that this function forward-referenced via
5913 // blockaddresses.
5914 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005915}
5916
Rafael Espindola79753a02015-12-18 21:18:57 +00005917std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005918 if (std::error_code EC = materializeMetadata())
5919 return EC;
5920
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005921 // Promise to materialize all forward references.
5922 WillMaterializeAllForwardRefs = true;
5923
Chris Lattner06310bf2009-06-16 05:15:21 +00005924 // Iterate over the module, deserializing any functions that are still on
5925 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005926 for (Function &F : *TheModule) {
5927 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005928 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005929 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005930 // At this point, if there are any function bodies, parse the rest of
5931 // the bits in the module past the last function block we have recorded
5932 // through either lazy scanning or the VST.
5933 if (LastFunctionBlockBit || NextUnreadBit)
5934 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5935 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005936
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005937 // Check that all block address forward references got resolved (as we
5938 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005939 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005940 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005941
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005942 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5943 // delete the old functions to clean up. We can't do this unless the entire
5944 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005945 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005946 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005947 for (auto *U : I.first->users()) {
5948 if (CallInst *CI = dyn_cast<CallInst>(U))
5949 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005950 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005951 if (!I.first->use_empty())
5952 I.first->replaceAllUsesWith(I.second);
5953 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005954 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005955 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00005956 // Do the same for remangled intrinsics
5957 for (auto &I : RemangledIntrinsics) {
5958 I.first->replaceAllUsesWith(I.second);
5959 I.first->eraseFromParent();
5960 }
5961 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005962
Rafael Espindola79753a02015-12-18 21:18:57 +00005963 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00005964
5965 UpgradeModuleFlags(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005966 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005967}
5968
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005969std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5970 return IdentifiedStructTypes;
5971}
5972
Teresa Johnson26ab5772016-03-15 00:04:37 +00005973std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005974 return ::error(DiagnosticHandler,
5975 make_error_code(BitcodeError::CorruptedBitcode), Message);
5976}
5977
Teresa Johnson26ab5772016-03-15 00:04:37 +00005978ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005979 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005980 bool CheckGlobalValSummaryPresenceOnly)
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00005981 : BitcodeReaderBase(Buffer),
5982 DiagnosticHandler(std::move(DiagnosticHandler)),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005983 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005984
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005985std::pair<GlobalValue::GUID, GlobalValue::GUID>
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005986ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005987 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5988 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5989 return VGI->second;
5990}
5991
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005992// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00005993// blocks where we don't actually create global values. The parsed information
5994// is saved in the bitcode reader for use when later parsing summaries.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005995std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005996 uint64_t Offset,
5997 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5998 assert(Offset > 0 && "Expected non-zero VST offset");
5999 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
6000
Teresa Johnson403a7872015-10-04 14:33:43 +00006001 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
6002 return error("Invalid record");
6003
6004 SmallVector<uint64_t, 64> Record;
6005
6006 // Read all the records for this value table.
6007 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006008
6009 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006010 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6011
6012 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006013 case BitstreamEntry::SubBlock: // Handled for us already.
6014 case BitstreamEntry::Error:
6015 return error("Malformed block");
6016 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006017 // Done parsing VST, jump back to wherever we came from.
6018 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006019 return std::error_code();
6020 case BitstreamEntry::Record:
6021 // The interesting case.
6022 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006023 }
6024
6025 // Read a record.
6026 Record.clear();
6027 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006028 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
6029 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006030 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
6031 if (convertToString(Record, 1, ValueName))
6032 return error("Invalid record");
6033 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006034 assert(!SourceFileName.empty());
6035 auto VLI = ValueIdToLinkageMap.find(ValueID);
6036 assert(VLI != ValueIdToLinkageMap.end() &&
6037 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006038 auto Linkage = VLI->second;
6039 std::string GlobalId =
6040 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00006041 auto ValueGUID = GlobalValue::getGUID(GlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006042 auto OriginalNameID = ValueGUID;
6043 if (GlobalValue::isLocalLinkage(Linkage))
6044 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00006045 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006046 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
6047 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006048 ValueIdToCallGraphGUIDMap[ValueID] =
6049 std::make_pair(ValueGUID, OriginalNameID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006050 ValueName.clear();
6051 break;
6052 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006053 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00006054 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006055 if (convertToString(Record, 2, ValueName))
6056 return error("Invalid record");
6057 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006058 assert(!SourceFileName.empty());
6059 auto VLI = ValueIdToLinkageMap.find(ValueID);
6060 assert(VLI != ValueIdToLinkageMap.end() &&
6061 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006062 auto Linkage = VLI->second;
Teresa Johnsonb43027d2016-03-15 02:13:19 +00006063 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
6064 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00006065 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006066 auto OriginalNameID = FunctionGUID;
6067 if (GlobalValue::isLocalLinkage(Linkage))
6068 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00006069 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006070 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
6071 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006072 ValueIdToCallGraphGUIDMap[ValueID] =
6073 std::make_pair(FunctionGUID, OriginalNameID);
Teresa Johnson403a7872015-10-04 14:33:43 +00006074
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006075 ValueName.clear();
6076 break;
6077 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006078 case bitc::VST_CODE_COMBINED_ENTRY: {
6079 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6080 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00006081 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006082 // The "original name", which is the second value of the pair will be
6083 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6084 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006085 break;
6086 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006087 }
6088 }
6089}
6090
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006091// Parse just the blocks needed for building the index out of the module.
6092// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00006093// from global value id to GlobalValueSummary objects.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006094std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006095 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6096 return error("Invalid record");
6097
Teresa Johnsone1164de2016-02-10 21:55:02 +00006098 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006099 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6100 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00006101
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006102 // Read the index for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00006103 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006104 BitstreamEntry Entry = Stream.advance();
6105
6106 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006107 case BitstreamEntry::Error:
6108 return error("Malformed block");
6109 case BitstreamEntry::EndBlock:
6110 return std::error_code();
6111
6112 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006113 if (CheckGlobalValSummaryPresenceOnly) {
6114 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
6115 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00006116 // No need to parse the rest since we found the summary.
6117 return std::error_code();
6118 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006119 if (Stream.SkipBlock())
6120 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00006121 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006122 }
6123 switch (Entry.ID) {
6124 default: // Skip unknown content.
6125 if (Stream.SkipBlock())
6126 return error("Invalid record");
6127 break;
6128 case bitc::BLOCKINFO_BLOCK_ID:
6129 // Need to parse these to get abbrev ids (e.g. for VST)
Peter Collingbourne939c7d92016-11-08 04:16:57 +00006130 if (readBlockInfo())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006131 return error("Malformed block");
6132 break;
6133 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006134 // Should have been parsed earlier via VSTOffset, unless there
6135 // is no summary section.
6136 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6137 !SeenGlobalValSummary) &&
6138 "Expected early VST parse via VSTOffset record");
6139 if (Stream.SkipBlock())
6140 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006141 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006142 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006143 assert(!SeenValueSymbolTable &&
6144 "Already read VST when parsing summary block?");
Teresa Johnson620c1402016-09-20 23:07:17 +00006145 // We might not have a VST if there were no values in the
6146 // summary. An empty summary block generated when we are
6147 // performing ThinLTO compiles so we don't later invoke
6148 // the regular LTO process on them.
6149 if (VSTOffset > 0) {
6150 if (std::error_code EC =
6151 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6152 return EC;
6153 SeenValueSymbolTable = true;
6154 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006155 SeenGlobalValSummary = true;
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006156 if (std::error_code EC = parseEntireSummary())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006157 return EC;
6158 break;
6159 case bitc::MODULE_STRTAB_BLOCK_ID:
6160 if (std::error_code EC = parseModuleStringTable())
6161 return EC;
6162 break;
6163 }
6164 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00006165
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006166 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00006167 Record.clear();
6168 auto BitCode = Stream.readRecord(Entry.ID, Record);
6169 switch (BitCode) {
6170 default:
6171 break; // Default behavior, ignore unknown content.
6172 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006173 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00006174 SmallString<128> ValueName;
6175 if (convertToString(Record, 0, ValueName))
6176 return error("Invalid record");
6177 SourceFileName = ValueName.c_str();
6178 break;
6179 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006180 /// MODULE_CODE_HASH: [5*i32]
6181 case bitc::MODULE_CODE_HASH: {
6182 if (Record.size() != 5)
6183 return error("Invalid hash length " + Twine(Record.size()).str());
6184 if (!TheIndex)
6185 break;
6186 if (TheIndex->modulePaths().empty())
Mehdi Amini00fa1402016-10-08 04:44:18 +00006187 // We always seed the index with the module.
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006188 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006189 if (TheIndex->modulePaths().size() != 1)
6190 return error("Don't expect multiple modules defined?");
6191 auto &Hash = TheIndex->modulePaths().begin()->second.second;
6192 int Pos = 0;
6193 for (auto &Val : Record) {
6194 assert(!(Val >> 32) && "Unexpected high bits set");
6195 Hash[Pos++] = Val;
6196 }
6197 break;
6198 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006199 /// MODULE_CODE_VSTOFFSET: [offset]
6200 case bitc::MODULE_CODE_VSTOFFSET:
6201 if (Record.size() < 1)
6202 return error("Invalid record");
6203 VSTOffset = Record[0];
6204 break;
6205 // GLOBALVAR: [pointer type, isconst, initid,
6206 // linkage, alignment, section, visibility, threadlocal,
6207 // unnamed_addr, externally_initialized, dllstorageclass,
6208 // comdat]
6209 case bitc::MODULE_CODE_GLOBALVAR: {
6210 if (Record.size() < 6)
6211 return error("Invalid record");
6212 uint64_t RawLinkage = Record[3];
6213 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6214 ValueIdToLinkageMap[ValueId++] = Linkage;
6215 break;
6216 }
6217 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
6218 // alignment, section, visibility, gc, unnamed_addr,
6219 // prologuedata, dllstorageclass, comdat, prefixdata]
6220 case bitc::MODULE_CODE_FUNCTION: {
6221 if (Record.size() < 8)
6222 return error("Invalid record");
6223 uint64_t RawLinkage = Record[3];
6224 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6225 ValueIdToLinkageMap[ValueId++] = Linkage;
6226 break;
6227 }
6228 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
6229 // dllstorageclass]
6230 case bitc::MODULE_CODE_ALIAS: {
6231 if (Record.size() < 6)
6232 return error("Invalid record");
6233 uint64_t RawLinkage = Record[3];
6234 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6235 ValueIdToLinkageMap[ValueId++] = Linkage;
6236 break;
6237 }
6238 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00006239 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006240 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00006241 }
6242 }
6243}
6244
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006245// Eagerly parse the entire summary block. This populates the GlobalValueSummary
6246// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006247std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006248 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00006249 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006250 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00006251
6252 // Parse version
6253 {
6254 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6255 if (Entry.Kind != BitstreamEntry::Record)
6256 return error("Invalid Summary Block: record for version expected");
6257 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
6258 return error("Invalid Summary Block: version expected");
6259 }
6260 const uint64_t Version = Record[0];
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006261 const bool IsOldProfileFormat = Version == 1;
6262 if (!IsOldProfileFormat && Version != 2)
6263 return error("Invalid summary version " + Twine(Version) +
6264 ", 1 or 2 expected");
Mehdi Amini8fe69362016-04-24 03:18:11 +00006265 Record.clear();
6266
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006267 // Keep around the last seen summary to be used when we see an optional
6268 // "OriginalName" attachement.
6269 GlobalValueSummary *LastSeenSummary = nullptr;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006270 bool Combined = false;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006271
6272 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006273 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6274
6275 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006276 case BitstreamEntry::SubBlock: // Handled for us already.
6277 case BitstreamEntry::Error:
6278 return error("Malformed block");
6279 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006280 // For a per-module index, remove any entries that still have empty
6281 // summaries. The VST parsing creates entries eagerly for all symbols,
6282 // but not all have associated summaries (e.g. it doesn't know how to
6283 // distinguish between VST_CODE_ENTRY for function declarations vs global
6284 // variables with initializers that end up with a summary). Remove those
6285 // entries now so that we don't need to rely on the combined index merger
6286 // to clean them up (especially since that may not run for the first
6287 // module's index if we merge into that).
6288 if (!Combined)
6289 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006290 return std::error_code();
6291 case BitstreamEntry::Record:
6292 // The interesting case.
6293 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006294 }
6295
6296 // Read a record. The record format depends on whether this
6297 // is a per-module index or a combined index file. In the per-module
6298 // case the records contain the associated value's ID for correlation
6299 // with VST entries. In the combined index the correlation is done
6300 // via the bitcode offset of the summary records (which were saved
6301 // in the combined index VST entries). The records also contain
6302 // information used for ThinLTO renaming and importing.
6303 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006304 auto BitCode = Stream.readRecord(Entry.ID, Record);
6305 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006306 default: // Default behavior: ignore.
6307 break;
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006308 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006309 // n x (valueid)]
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006310 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006311 // numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006312 // n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006313 case bitc::FS_PERMODULE:
6314 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006315 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006316 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006317 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006318 unsigned NumRefs = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006319 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6320 std::unique_ptr<FunctionSummary> FS =
6321 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006322 // The module path string ref set in the summary must be owned by the
6323 // index's module string table. Since we don't have a module path
6324 // string table section in the per-module index, we create a single
6325 // module path string table entry with an empty (0) ID to take
6326 // ownership.
6327 FS->setModulePath(
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006328 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006329 static int RefListStartIndex = 4;
6330 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6331 assert(Record.size() >= RefListStartIndex + NumRefs &&
6332 "Record size inconsistent with number of references");
6333 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6334 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006335 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006336 FS->addRefEdge(RefGUID);
6337 }
6338 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6339 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6340 ++I) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006341 CalleeInfo::HotnessType Hotness;
6342 GlobalValue::GUID CalleeGUID;
6343 std::tie(CalleeGUID, Hotness) =
6344 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile);
6345 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006346 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006347 auto GUID = getGUIDFromValueId(ValueID);
6348 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006349 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006350 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006351 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006352 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006353 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6354 // they expect all aliasee summaries to be available.
6355 case bitc::FS_ALIAS: {
6356 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006357 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006358 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006359 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6360 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006361 // The module path string ref set in the summary must be owned by the
6362 // index's module string table. Since we don't have a module path
6363 // string table section in the per-module index, we create a single
6364 // module path string table entry with an empty (0) ID to take
6365 // ownership.
6366 AS->setModulePath(
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006367 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006368
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006369 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006370 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
6371 if (!AliaseeSummary)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006372 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson28e457b2016-04-24 14:57:11 +00006373 AS->setAliasee(AliaseeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006374
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006375 auto GUID = getGUIDFromValueId(ValueID);
6376 AS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006377 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006378 break;
6379 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006380 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006381 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6382 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006383 uint64_t RawFlags = Record[1];
6384 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006385 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006386 llvm::make_unique<GlobalVarSummary>(Flags);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006387 FS->setModulePath(
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006388 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006389 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6390 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006391 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006392 FS->addRefEdge(RefGUID);
6393 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006394 auto GUID = getGUIDFromValueId(ValueID);
6395 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006396 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006397 break;
6398 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006399 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006400 // numrefs x valueid, n x (valueid)]
Teresa Johnson02e98332016-04-27 13:28:35 +00006401 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006402 // numrefs x valueid, n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006403 case bitc::FS_COMBINED:
6404 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006405 unsigned ValueID = Record[0];
6406 uint64_t ModuleId = Record[1];
6407 uint64_t RawFlags = Record[2];
6408 unsigned InstCount = Record[3];
6409 unsigned NumRefs = Record[4];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006410 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6411 std::unique_ptr<FunctionSummary> FS =
6412 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006413 LastSeenSummary = FS.get();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006414 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006415 static int RefListStartIndex = 5;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006416 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6417 assert(Record.size() >= RefListStartIndex + NumRefs &&
6418 "Record size inconsistent with number of references");
Teresa Johnson02e98332016-04-27 13:28:35 +00006419 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
6420 ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006421 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006422 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006423 FS->addRefEdge(RefGUID);
6424 }
6425 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6426 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6427 ++I) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006428 CalleeInfo::HotnessType Hotness;
6429 GlobalValue::GUID CalleeGUID;
6430 std::tie(CalleeGUID, Hotness) =
6431 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile);
6432 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006433 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006434 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006435 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006436 Combined = true;
6437 break;
6438 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006439 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006440 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6441 // they expect all aliasee summaries to be available.
6442 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006443 unsigned ValueID = Record[0];
6444 uint64_t ModuleId = Record[1];
6445 uint64_t RawFlags = Record[2];
6446 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006447 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6448 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006449 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006450 AS->setModulePath(ModuleIdMap[ModuleId]);
6451
Teresa Johnson02e98332016-04-27 13:28:35 +00006452 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
6453 auto AliaseeInModule =
6454 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
6455 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006456 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00006457 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006458
Teresa Johnson02e98332016-04-27 13:28:35 +00006459 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006460 TheIndex->addGlobalValueSummary(GUID, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006461 Combined = true;
6462 break;
6463 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006464 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006465 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006466 unsigned ValueID = Record[0];
6467 uint64_t ModuleId = Record[1];
6468 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006469 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006470 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006471 llvm::make_unique<GlobalVarSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006472 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006473 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006474 for (unsigned I = 3, E = Record.size(); I != E; ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006475 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006476 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006477 FS->addRefEdge(RefGUID);
6478 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006479 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006480 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006481 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006482 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006483 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006484 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6485 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6486 uint64_t OriginalName = Record[0];
6487 if (!LastSeenSummary)
6488 return error("Name attachment that does not follow a combined record");
6489 LastSeenSummary->setOriginalName(OriginalName);
6490 // Reset the LastSeenSummary
6491 LastSeenSummary = nullptr;
6492 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006493 }
6494 }
6495 llvm_unreachable("Exit infinite loop");
6496}
6497
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00006498std::pair<GlobalValue::GUID, CalleeInfo::HotnessType>
6499ModuleSummaryIndexBitcodeReader::readCallGraphEdge(
6500 const SmallVector<uint64_t, 64> &Record, unsigned int &I,
6501 const bool IsOldProfileFormat, const bool HasProfile) {
6502
6503 auto Hotness = CalleeInfo::HotnessType::Unknown;
6504 unsigned CalleeValueId = Record[I];
6505 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
6506 if (IsOldProfileFormat) {
6507 I += 1; // Skip old callsitecount field
6508 if (HasProfile)
6509 I += 1; // Skip old profilecount field
6510 } else if (HasProfile)
6511 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6512 return {CalleeGUID, Hotness};
6513}
6514
Teresa Johnson403a7872015-10-04 14:33:43 +00006515// Parse the module string table block into the Index.
6516// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006517std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006518 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6519 return error("Invalid record");
6520
6521 SmallVector<uint64_t, 64> Record;
6522
6523 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006524 ModulePathStringTableTy::iterator LastSeenModulePath;
Eugene Zelenko1804a772016-08-25 00:45:04 +00006525
6526 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006527 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6528
6529 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006530 case BitstreamEntry::SubBlock: // Handled for us already.
6531 case BitstreamEntry::Error:
6532 return error("Malformed block");
6533 case BitstreamEntry::EndBlock:
6534 return std::error_code();
6535 case BitstreamEntry::Record:
6536 // The interesting case.
6537 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006538 }
6539
6540 Record.clear();
6541 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006542 default: // Default behavior: ignore.
6543 break;
6544 case bitc::MST_CODE_ENTRY: {
6545 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006546 uint64_t ModuleId = Record[0];
6547
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006548 if (convertToString(Record, 1, ModulePath))
6549 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006550
6551 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6552 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6553
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006554 ModulePath.clear();
6555 break;
6556 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006557 /// MST_CODE_HASH: [5*i32]
6558 case bitc::MST_CODE_HASH: {
6559 if (Record.size() != 5)
6560 return error("Invalid hash length " + Twine(Record.size()).str());
6561 if (LastSeenModulePath == TheIndex->modulePaths().end())
6562 return error("Invalid hash that does not follow a module path");
6563 int Pos = 0;
6564 for (auto &Val : Record) {
6565 assert(!(Val >> 32) && "Unexpected high bits set");
6566 LastSeenModulePath->second.second[Pos++] = Val;
6567 }
6568 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6569 LastSeenModulePath = TheIndex->modulePaths().end();
6570 break;
6571 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006572 }
6573 }
6574 llvm_unreachable("Exit infinite loop");
6575}
6576
6577// Parse the function info index from the bitcode streamer into the given index.
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00006578std::error_code
6579ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006580 TheIndex = I;
6581
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00006582 if (std::error_code EC = initStream())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006583 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006584
6585 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006586 if (!hasValidBitcodeHeader(Stream))
6587 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006588
6589 // We expect a number of well-defined blocks, though we don't necessarily
6590 // need to understand them all.
Eugene Zelenko1804a772016-08-25 00:45:04 +00006591 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006592 if (Stream.AtEndOfStream()) {
6593 // We didn't really read a proper Module block.
6594 return error("Malformed block");
6595 }
6596
6597 BitstreamEntry Entry =
6598 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6599
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006600 if (Entry.Kind != BitstreamEntry::SubBlock)
6601 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00006602
6603 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6604 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006605 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6606 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00006607
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006608 if (Stream.SkipBlock())
6609 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006610 }
6611}
6612
Rafael Espindola48da4f42013-11-04 16:16:24 +00006613namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +00006614
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00006615// FIXME: This class is only here to support the transition to llvm::Error. It
6616// will be removed once this transition is complete. Clients should prefer to
6617// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00006618class BitcodeErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +00006619 const char *name() const noexcept override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006620 return "llvm.bitcode";
6621 }
Craig Topper73156022014-03-02 09:09:27 +00006622 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006623 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006624 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006625 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006626 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006627 case BitcodeError::CorruptedBitcode:
6628 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006629 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006630 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006631 }
6632};
Eugene Zelenko1804a772016-08-25 00:45:04 +00006633
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006634} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006635
Chris Bieneman770163e2014-09-19 20:29:02 +00006636static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6637
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006638const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006639 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006640}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006641
Chris Lattner6694f602007-04-29 07:54:31 +00006642//===----------------------------------------------------------------------===//
6643// External interface
6644//===----------------------------------------------------------------------===//
6645
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006646/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006647///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006648/// This isn't always used in a lazy context. In particular, it's also used by
6649/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6650/// in forward-referenced functions from block address references.
6651///
Rafael Espindola728074b2015-06-17 00:40:56 +00006652/// \param[in] MaterializeAll Set to \c true if we should materialize
6653/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006654static ErrorOr<std::unique_ptr<Module>>
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006655getLazyBitcodeModuleImpl(MemoryBufferRef Buffer, LLVMContext &Context,
6656 bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006657 bool ShouldLazyLoadMetadata = false) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006658 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006659
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006660 std::unique_ptr<Module> M =
6661 llvm::make_unique<Module>(Buffer.getBufferIdentifier(), Context);
6662 M->setMaterializer(R);
Rafael Espindolab7993462012-01-02 07:49:53 +00006663
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006664 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6665 if (std::error_code EC = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata))
6666 return EC;
6667
6668 if (MaterializeAll) {
6669 // Read in the entire module, and destroy the BitcodeReader.
6670 if (std::error_code EC = M->materializeAll())
6671 return EC;
6672 } else {
6673 // Resolve forward references from blockaddresses.
6674 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6675 return EC;
6676 }
6677 return std::move(M);
Chris Lattner6694f602007-04-29 07:54:31 +00006678}
6679
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006680ErrorOr<std::unique_ptr<Module>>
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006681llvm::getLazyBitcodeModule(MemoryBufferRef Buffer,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006682 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006683 return getLazyBitcodeModuleImpl(Buffer, Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006684 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006685}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006686
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006687ErrorOr<std::unique_ptr<Module>>
6688llvm::getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6689 LLVMContext &Context,
6690 bool ShouldLazyLoadMetadata) {
6691 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata);
6692 if (MOrErr)
6693 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
6694 return MOrErr;
6695}
6696
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006697ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6698 LLVMContext &Context) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006699 return getLazyBitcodeModuleImpl(Buffer, Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006700 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6701 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006702}
Bill Wendling0198ce02010-10-06 01:22:42 +00006703
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006704std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6705 LLVMContext &Context) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006706 BitcodeReader R(Buffer, Context);
6707 ErrorOr<std::string> Triple = R.parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006708 if (Triple.getError())
6709 return "";
6710 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006711}
Teresa Johnson403a7872015-10-04 14:33:43 +00006712
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00006713bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
6714 LLVMContext &Context) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006715 BitcodeReader R(Buffer, Context);
6716 ErrorOr<bool> hasObjCCategory = R.hasObjCCategory();
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00006717 if (hasObjCCategory.getError())
6718 return false;
6719 return hasObjCCategory.get();
6720}
6721
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006722std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6723 LLVMContext &Context) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006724 BitcodeReader R(Buffer, Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006725 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6726 if (ProducerString.getError())
6727 return "";
6728 return ProducerString.get();
6729}
6730
Teresa Johnson403a7872015-10-04 14:33:43 +00006731// Parse the specified bitcode buffer, returning the function info index.
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00006732ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
6733 MemoryBufferRef Buffer,
6734 const DiagnosticHandlerFunction &DiagnosticHandler) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006735 ModuleSummaryIndexBitcodeReader R(Buffer, DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006736
Teresa Johnson26ab5772016-03-15 00:04:37 +00006737 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006738
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00006739 if (std::error_code EC = R.parseSummaryIndexInto(Index.get()))
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006740 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006741
Teresa Johnson403a7872015-10-04 14:33:43 +00006742 return std::move(Index);
6743}
6744
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006745// Check if the given bitcode buffer contains a global value summary block.
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00006746bool llvm::hasGlobalValueSummary(
6747 MemoryBufferRef Buffer,
6748 const DiagnosticHandlerFunction &DiagnosticHandler) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006749 ModuleSummaryIndexBitcodeReader R(Buffer, DiagnosticHandler, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006750
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006751 if (R.parseSummaryIndexInto(nullptr))
Teresa Johnson403a7872015-10-04 14:33:43 +00006752 return false;
Teresa Johnson403a7872015-10-04 14:33:43 +00006753
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006754 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006755}