blob: 538aad09cf52479e96df8f83d5a0229f04186a82 [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
Teresa Johnsonad176792016-11-11 05:34:58 +000010#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Aminief27db82016-12-12 19:34:26 +000011#include "MetadataLoader.h"
12#include "ValueList.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000013#include "llvm/ADT/APFloat.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000017#include "llvm/ADT/Optional.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/SmallVector.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000021#include "llvm/ADT/StringRef.h"
David Majnemer3087b222015-01-20 05:58:07 +000022#include "llvm/ADT/Triple.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000023#include "llvm/ADT/Twine.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000024#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000025#include "llvm/Bitcode/LLVMBitCodes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000028#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/BasicBlock.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000031#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000032#include "llvm/IR/Comdat.h"
33#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Constants.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000035#include "llvm/IR/DataLayout.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000036#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000037#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/Function.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000041#include "llvm/IR/GVMaterializer.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000042#include "llvm/IR/GlobalAlias.h"
43#include "llvm/IR/GlobalIFunc.h"
44#include "llvm/IR/GlobalIndirectSymbol.h"
45#include "llvm/IR/GlobalObject.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/InlineAsm.h"
Mehdi Amini86623052016-12-16 19:16:29 +000049#include "llvm/IR/InstIterator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
53#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000054#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000055#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000057#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000059#include "llvm/IR/Type.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000060#include "llvm/IR/Value.h"
Mehdi Amini86623052016-12-16 19:16:29 +000061#include "llvm/IR/Verifier.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000062#include "llvm/Support/AtomicOrdering.h"
63#include "llvm/Support/Casting.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000064#include "llvm/Support/CommandLine.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000065#include "llvm/Support/Compiler.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000066#include "llvm/Support/Debug.h"
Peter Collingbourne58f7f072016-11-09 00:51:04 +000067#include "llvm/Support/Error.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000068#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000069#include "llvm/Support/ErrorOr.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000070#include "llvm/Support/ManagedStatic.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000071#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000072#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000073#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000074#include <algorithm>
75#include <cassert>
76#include <cstddef>
77#include <cstdint>
Benjamin Kramercced8be2015-03-17 20:40:24 +000078#include <deque>
Eugene Zelenko1804a772016-08-25 00:45:04 +000079#include <map>
80#include <memory>
Eugene Zelenko975293f2017-09-07 23:28:24 +000081#include <set>
Eugene Zelenko1804a772016-08-25 00:45:04 +000082#include <string>
83#include <system_error>
84#include <tuple>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000085#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000086#include <vector>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000087
Chris Lattner1314b992007-04-22 06:23:29 +000088using namespace llvm;
89
Teresa Johnson916495d2016-04-04 18:52:58 +000090static cl::opt<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden,
92 cl::desc(
93 "Print the global id for each value when reading the module summary"));
94
Benjamin Kramercced8be2015-03-17 20:40:24 +000095namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +000096
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000097enum {
98 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99};
100
Eugene Zelenko975293f2017-09-07 23:28:24 +0000101} // end anonymous namespace
102
103static Error error(const Twine &Message) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000104 return make_error<StringError>(
105 Message, make_error_code(BitcodeError::CorruptedBitcode));
106}
107
108/// Helper to read the header common to all bitcode files.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000109static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000110 // Sniff for the signature.
111 if (!Stream.canSkipToPos(4) ||
112 Stream.Read(8) != 'B' ||
113 Stream.Read(8) != 'C' ||
114 Stream.Read(4) != 0x0 ||
115 Stream.Read(4) != 0xC ||
116 Stream.Read(4) != 0xE ||
117 Stream.Read(4) != 0xD)
118 return false;
119 return true;
120}
121
Eugene Zelenko975293f2017-09-07 23:28:24 +0000122static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000123 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
124 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
125
126 if (Buffer.getBufferSize() & 3)
127 return error("Invalid bitcode signature");
128
129 // If we have a wrapper header, parse it and ignore the non-bc file contents.
130 // The magic number is 0x0B17C0DE stored in little endian.
131 if (isBitcodeWrapper(BufPtr, BufEnd))
132 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
133 return error("Invalid bitcode wrapper header");
134
135 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
136 if (!hasValidBitcodeHeader(Stream))
137 return error("Invalid bitcode signature");
138
139 return std::move(Stream);
140}
141
Peter Collingbournecd513a42016-11-11 19:50:24 +0000142/// Convert a string from a record into an std::string, return true on failure.
143template <typename StrTy>
144static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
145 StrTy &Result) {
146 if (Idx > Record.size())
147 return true;
148
149 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
150 Result += (char)Record[i];
151 return false;
152}
153
Mehdi Amini86623052016-12-16 19:16:29 +0000154// Strip all the TBAA attachment for the module.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000155static void stripTBAA(Module *M) {
Mehdi Amini86623052016-12-16 19:16:29 +0000156 for (auto &F : *M) {
157 if (F.isMaterializable())
158 continue;
159 for (auto &I : instructions(F))
160 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
161 }
162}
163
Peter Collingbournecd513a42016-11-11 19:50:24 +0000164/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
165/// "epoch" encoded in the bitcode, and return the producer name if any.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000166static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000167 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
168 return error("Invalid record");
169
170 // Read all the records.
171 SmallVector<uint64_t, 64> Record;
172
173 std::string ProducerIdentification;
174
175 while (true) {
176 BitstreamEntry Entry = Stream.advance();
177
178 switch (Entry.Kind) {
179 default:
180 case BitstreamEntry::Error:
181 return error("Malformed block");
182 case BitstreamEntry::EndBlock:
183 return ProducerIdentification;
184 case BitstreamEntry::Record:
185 // The interesting case.
186 break;
187 }
188
189 // Read a record.
190 Record.clear();
191 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
192 switch (BitCode) {
193 default: // Default behavior: reject
194 return error("Invalid value");
195 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
196 convertToString(Record, 0, ProducerIdentification);
197 break;
198 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
199 unsigned epoch = (unsigned)Record[0];
200 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
201 return error(
202 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
203 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
204 }
205 }
206 }
207 }
208}
209
Eugene Zelenko975293f2017-09-07 23:28:24 +0000210static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000211 // We expect a number of well-defined blocks, though we don't necessarily
212 // need to understand them all.
213 while (true) {
214 if (Stream.AtEndOfStream())
215 return "";
216
217 BitstreamEntry Entry = Stream.advance();
218 switch (Entry.Kind) {
219 case BitstreamEntry::EndBlock:
220 case BitstreamEntry::Error:
221 return error("Malformed block");
222
223 case BitstreamEntry::SubBlock:
224 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
225 return readIdentificationBlock(Stream);
226
227 // Ignore other sub-blocks.
228 if (Stream.SkipBlock())
229 return error("Malformed block");
230 continue;
231 case BitstreamEntry::Record:
232 Stream.skipRecord(Entry.ID);
233 continue;
234 }
235 }
236}
237
Eugene Zelenko975293f2017-09-07 23:28:24 +0000238static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000239 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
240 return error("Invalid record");
241
242 SmallVector<uint64_t, 64> Record;
243 // Read all the records for this module.
244
245 while (true) {
246 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
247
248 switch (Entry.Kind) {
249 case BitstreamEntry::SubBlock: // Handled for us already.
250 case BitstreamEntry::Error:
251 return error("Malformed block");
252 case BitstreamEntry::EndBlock:
253 return false;
254 case BitstreamEntry::Record:
255 // The interesting case.
256 break;
257 }
258
259 // Read a record.
260 switch (Stream.readRecord(Entry.ID, Record)) {
261 default:
262 break; // Default behavior, ignore unknown content.
263 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
264 std::string S;
265 if (convertToString(Record, 0, S))
266 return error("Invalid record");
267 // Check for the i386 and other (x86_64, ARM) conventions
268 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
269 S.find("__OBJC,__category") != std::string::npos)
270 return true;
271 break;
272 }
273 }
274 Record.clear();
275 }
276 llvm_unreachable("Exit infinite loop");
277}
278
Eugene Zelenko975293f2017-09-07 23:28:24 +0000279static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000280 // We expect a number of well-defined blocks, though we don't necessarily
281 // need to understand them all.
282 while (true) {
283 BitstreamEntry Entry = Stream.advance();
284
285 switch (Entry.Kind) {
286 case BitstreamEntry::Error:
287 return error("Malformed block");
288 case BitstreamEntry::EndBlock:
289 return false;
290
291 case BitstreamEntry::SubBlock:
292 if (Entry.ID == bitc::MODULE_BLOCK_ID)
293 return hasObjCCategoryInModule(Stream);
294
295 // Ignore other sub-blocks.
296 if (Stream.SkipBlock())
297 return error("Malformed block");
298 continue;
299
300 case BitstreamEntry::Record:
301 Stream.skipRecord(Entry.ID);
302 continue;
303 }
304 }
305}
306
Eugene Zelenko975293f2017-09-07 23:28:24 +0000307static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000308 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
309 return error("Invalid record");
310
311 SmallVector<uint64_t, 64> Record;
312
313 std::string Triple;
314
315 // Read all the records for this module.
316 while (true) {
317 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
318
319 switch (Entry.Kind) {
320 case BitstreamEntry::SubBlock: // Handled for us already.
321 case BitstreamEntry::Error:
322 return error("Malformed block");
323 case BitstreamEntry::EndBlock:
324 return Triple;
325 case BitstreamEntry::Record:
326 // The interesting case.
327 break;
328 }
329
330 // Read a record.
331 switch (Stream.readRecord(Entry.ID, Record)) {
332 default: break; // Default behavior, ignore unknown content.
333 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
334 std::string S;
335 if (convertToString(Record, 0, S))
336 return error("Invalid record");
337 Triple = S;
338 break;
339 }
340 }
341 Record.clear();
342 }
343 llvm_unreachable("Exit infinite loop");
344}
345
Eugene Zelenko975293f2017-09-07 23:28:24 +0000346static Expected<std::string> readTriple(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000347 // We expect a number of well-defined blocks, though we don't necessarily
348 // need to understand them all.
349 while (true) {
350 BitstreamEntry Entry = Stream.advance();
351
352 switch (Entry.Kind) {
353 case BitstreamEntry::Error:
354 return error("Malformed block");
355 case BitstreamEntry::EndBlock:
356 return "";
357
358 case BitstreamEntry::SubBlock:
359 if (Entry.ID == bitc::MODULE_BLOCK_ID)
360 return readModuleTriple(Stream);
361
362 // Ignore other sub-blocks.
363 if (Stream.SkipBlock())
364 return error("Malformed block");
365 continue;
366
367 case BitstreamEntry::Record:
368 Stream.skipRecord(Entry.ID);
369 continue;
370 }
371 }
372}
373
Eugene Zelenko975293f2017-09-07 23:28:24 +0000374namespace {
375
Peter Collingbourne6e860752016-09-23 18:27:42 +0000376class BitcodeReaderBase {
377protected:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000378 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
379 : Stream(std::move(Stream)), Strtab(Strtab) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000380 this->Stream.setBlockInfo(&BlockInfo);
381 }
Peter Collingbourne6e860752016-09-23 18:27:42 +0000382
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000383 BitstreamBlockInfo BlockInfo;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000384 BitstreamCursor Stream;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000385 StringRef Strtab;
386
387 /// In version 2 of the bitcode we store names of global values and comdats in
388 /// a string table rather than in the VST.
389 bool UseStrtab = false;
Peter Collingbourne6e860752016-09-23 18:27:42 +0000390
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000391 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
392
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000393 /// If this module uses a string table, pop the reference to the string table
394 /// and return the referenced string and the rest of the record. Otherwise
395 /// just return the record itself.
396 std::pair<StringRef, ArrayRef<uint64_t>>
397 readNameFromStrtab(ArrayRef<uint64_t> Record);
398
Peter Collingbourne939c7d92016-11-08 04:16:57 +0000399 bool readBlockInfo();
Peter Collingbourne6e860752016-09-23 18:27:42 +0000400
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000401 // Contains an arbitrary and optional string identifying the bitcode producer
402 std::string ProducerIdentification;
403
404 Error error(const Twine &Message);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000405};
406
Eugene Zelenko975293f2017-09-07 23:28:24 +0000407} // end anonymous namespace
408
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000409Error BitcodeReaderBase::error(const Twine &Message) {
410 std::string FullMsg = Message.str();
411 if (!ProducerIdentification.empty())
412 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
413 LLVM_VERSION_STRING "')";
Peter Collingbournec0032b72016-11-11 19:50:10 +0000414 return ::error(FullMsg);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000415}
416
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000417Expected<unsigned>
418BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
Eugene Zelenko975293f2017-09-07 23:28:24 +0000419 if (Record.empty())
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000420 return error("Invalid record");
421 unsigned ModuleVersion = Record[0];
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000422 if (ModuleVersion > 2)
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000423 return error("Invalid value");
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000424 UseStrtab = ModuleVersion >= 2;
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000425 return ModuleVersion;
426}
427
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000428std::pair<StringRef, ArrayRef<uint64_t>>
429BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
430 if (!UseStrtab)
431 return {"", Record};
432 // Invalid reference. Let the caller complain about the record being empty.
433 if (Record[0] + Record[1] > Strtab.size())
434 return {"", {}};
435 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
436}
437
Eugene Zelenko975293f2017-09-07 23:28:24 +0000438namespace {
439
Peter Collingbourne6e860752016-09-23 18:27:42 +0000440class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
441 LLVMContext &Context;
442 Module *TheModule = nullptr;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000443 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000444 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000445 // Last function offset found in the VST.
446 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000447 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000448 uint64_t VSTOffset = 0;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000449
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000450 std::vector<std::string> SectionTable;
451 std::vector<std::string> GCTable;
452
Benjamin Kramercced8be2015-03-17 20:40:24 +0000453 std::vector<Type*> TypeList;
454 BitcodeReaderValueList ValueList;
Mehdi Aminief27db82016-12-12 19:34:26 +0000455 Optional<MetadataLoader> MDLoader;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000456 std::vector<Comdat *> ComdatList;
457 SmallVector<Instruction *, 64> InstructionList;
458
Eugene Zelenko975293f2017-09-07 23:28:24 +0000459 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
460 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
461 std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
462 std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
463 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000464
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000465 /// The set of attributes by index. Index zero in the file is for null, and
466 /// is thus not represented here. As such all indices are off by one.
Reid Klecknerb5180542017-03-21 16:57:19 +0000467 std::vector<AttributeList> MAttributes;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000468
Karl Schimpf36440082015-08-31 16:43:55 +0000469 /// The set of attribute groups.
Reid Klecknerb5180542017-03-21 16:57:19 +0000470 std::map<unsigned, AttributeList> MAttributeGroups;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000471
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000472 /// While parsing a function body, this is a list of the basic blocks for the
473 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000474 std::vector<BasicBlock*> FunctionBBs;
475
476 // When reading the module header, this list is populated with functions that
477 // have bodies later in the file.
478 std::vector<Function*> FunctionsWithBodies;
479
480 // When intrinsic functions are encountered which require upgrading they are
481 // stored here with their replacement function.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000482 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000483 UpdatedIntrinsicMap UpgradedIntrinsics;
484 // Intrinsics which were remangled because of types rename
485 UpdatedIntrinsicMap RemangledIntrinsics;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000486
Benjamin Kramercced8be2015-03-17 20:40:24 +0000487 // Several operations happen after the module header has been read, but
488 // before function bodies are processed. This keeps track of whether
489 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000490 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000491
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000492 /// When function bodies are initially scanned, this map contains info about
493 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000494 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
495
496 /// When Metadata block is initially scanned when parsing the module, we may
497 /// choose to defer parsing of the metadata. This vector contains info about
498 /// which Metadata blocks are deferred.
499 std::vector<uint64_t> DeferredMetadataInfo;
500
501 /// These are basic blocks forward-referenced by block addresses. They are
502 /// inserted lazily into functions when they're loaded. The basic block ID is
503 /// its index into the vector.
504 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
505 std::deque<Function *> BasicBlockFwdRefQueue;
506
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000507 /// Indicates that we are using a new encoding for instruction operands where
508 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
509 /// instruction number, for a more compact encoding. Some instruction
510 /// operands are not relative to the instruction ID: basic block numbers, and
511 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000512 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000513 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000514
515 /// True if all functions will be materialized, negating the need to process
516 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000517 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000518
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000519 bool StripDebugInfo = false;
Mehdi Amini86623052016-12-16 19:16:29 +0000520 TBAAVerifier TBAAVerifyHelper;
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000521
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000522 std::vector<std::string> BundleTags;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000523 SmallVector<SyncScope::ID, 8> SSIDs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000524
Benjamin Kramercced8be2015-03-17 20:40:24 +0000525public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000526 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
527 StringRef ProducerIdentification, LLVMContext &Context);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000528
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000529 Error materializeForwardReferencedFunctions();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000530
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000531 Error materialize(GlobalValue *GV) override;
532 Error materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000533 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000534
Rafael Espindola6ace6852015-06-15 21:02:49 +0000535 /// \brief Main interface to parsing a bitcode buffer.
536 /// \returns true if an error occurred.
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000537 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
538 bool IsImporting = false);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000539
Benjamin Kramercced8be2015-03-17 20:40:24 +0000540 static uint64_t decodeSignRotatedValue(uint64_t V);
541
542 /// Materialize any deferred Metadata block.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000543 Error materializeMetadata() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000544
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000545 void setStripDebugInfo() override;
546
Benjamin Kramercced8be2015-03-17 20:40:24 +0000547private:
548 std::vector<StructType *> IdentifiedStructTypes;
549 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
550 StructType *createIdentifiedStructType(LLVMContext &Context);
551
552 Type *getTypeByID(unsigned ID);
Eugene Zelenko1804a772016-08-25 00:45:04 +0000553
David Majnemer8a1c45d2015-12-12 05:38:55 +0000554 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000555 if (Ty && Ty->isMetadataTy())
556 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000557 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000558 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000559
Benjamin Kramercced8be2015-03-17 20:40:24 +0000560 Metadata *getFnMetadataByID(unsigned ID) {
Mehdi Amini3bb4d012017-01-20 20:29:16 +0000561 return MDLoader->getMetadataFwdRefOrLoad(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000562 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000563
Benjamin Kramercced8be2015-03-17 20:40:24 +0000564 BasicBlock *getBasicBlock(unsigned ID) const {
565 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
566 return FunctionBBs[ID];
567 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000568
Reid Klecknerb5180542017-03-21 16:57:19 +0000569 AttributeList getAttributes(unsigned i) const {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000570 if (i-1 < MAttributes.size())
571 return MAttributes[i-1];
Reid Klecknerb5180542017-03-21 16:57:19 +0000572 return AttributeList();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000573 }
574
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000575 /// Read a value/type pair out of the specified record from slot 'Slot'.
576 /// Increment Slot past the number of slots used in the record. Return true on
577 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000578 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
579 unsigned InstNum, Value *&ResVal) {
580 if (Slot == Record.size()) return true;
581 unsigned ValNo = (unsigned)Record[Slot++];
582 // Adjust the ValNo, if it was encoded relative to the InstNum.
583 if (UseRelativeIDs)
584 ValNo = InstNum - ValNo;
585 if (ValNo < InstNum) {
586 // If this is not a forward reference, just return the value we already
587 // have.
588 ResVal = getFnValueByID(ValNo, nullptr);
589 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000590 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000591 if (Slot == Record.size())
592 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000593
594 unsigned TypeNo = (unsigned)Record[Slot++];
595 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
596 return ResVal == nullptr;
597 }
598
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000599 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
600 /// past the number of slots used by the value in the record. Return true if
601 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000602 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000603 unsigned InstNum, Type *Ty, Value *&ResVal) {
604 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000605 return true;
606 // All values currently take a single record slot.
607 ++Slot;
608 return false;
609 }
610
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000611 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000612 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000613 unsigned InstNum, Type *Ty, Value *&ResVal) {
614 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000615 return ResVal == nullptr;
616 }
617
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000618 /// Version of getValue that returns ResVal directly, or 0 if there is an
619 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000620 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000621 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000622 if (Slot == Record.size()) return nullptr;
623 unsigned ValNo = (unsigned)Record[Slot];
624 // Adjust the ValNo, if it was encoded relative to the InstNum.
625 if (UseRelativeIDs)
626 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000627 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000628 }
629
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000630 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000631 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000632 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000633 if (Slot == Record.size()) return nullptr;
634 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
635 // Adjust the ValNo, if it was encoded relative to the InstNum.
636 if (UseRelativeIDs)
637 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000638 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000639 }
640
641 /// Converts alignment exponent (i.e. power of two (or zero)) to the
642 /// corresponding alignment to use. If alignment is too large, returns
643 /// a corresponding error code.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000644 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
645 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
646 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000647
648 Error parseComdatRecord(ArrayRef<uint64_t> Record);
649 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
650 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
651 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
652 ArrayRef<uint64_t> Record);
653
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000654 Error parseAttributeBlock();
655 Error parseAttributeGroupBlock();
656 Error parseTypeTable();
657 Error parseTypeTableBody();
658 Error parseOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000659 Error parseSyncScopeNames();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000660
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000661 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
662 unsigned NameIndex, Triple &TT);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000663 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
664 ArrayRef<uint64_t> Record);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000665 Error parseValueSymbolTable(uint64_t Offset = 0);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000666 Error parseGlobalValueSymbolTable();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000667 Error parseConstants();
668 Error rememberAndSkipFunctionBodies();
669 Error rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000670 /// Save the positions of the Metadata blocks and skip parsing the blocks.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000671 Error rememberAndSkipMetadata();
672 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
673 Error parseFunctionBody(Function *F);
674 Error globalCleanup();
675 Error resolveGlobalAndIndirectSymbolInits();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000676 Error parseUseLists();
677 Error findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000678 Function *F,
679 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000680
681 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000682};
Teresa Johnson403a7872015-10-04 14:33:43 +0000683
684/// Class to manage reading and parsing function summary index bitcode
685/// files/sections.
Peter Collingbourne6e860752016-09-23 18:27:42 +0000686class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000687 /// The module index built during parsing.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +0000688 ModuleSummaryIndex &TheIndex;
Teresa Johnson403a7872015-10-04 14:33:43 +0000689
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000690 /// Indicates whether we have encountered a global value summary section
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000691 /// yet during parsing.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000692 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000693
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000694 /// Indicates whether we have already parsed the VST, used for error checking.
695 bool SeenValueSymbolTable = false;
696
697 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
698 /// Used to enable on-demand parsing of the VST.
699 uint64_t VSTOffset = 0;
700
Peter Collingbourne9667b912017-05-04 18:03:25 +0000701 // Map to save ValueId to ValueInfo association that was recorded in the
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000702 // ValueSymbolTable. It is used after the VST is parsed to convert
703 // call graph edges read from the function summary from referencing
Peter Collingbourne9667b912017-05-04 18:03:25 +0000704 // callees by their ValueId to using the ValueInfo instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000705 // they are recorded in the summary index being built.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000706 // We save a GUID which refers to the same global as the ValueInfo, but
707 // ignoring the linkage, i.e. for values other than local linkage they are
708 // identical.
709 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
710 ValueIdToValueInfoMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000711
Teresa Johnson403a7872015-10-04 14:33:43 +0000712 /// Map populated during module path string table parsing, from the
713 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000714 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000715 /// summary records.
716 DenseMap<uint64_t, StringRef> ModuleIdMap;
717
Teresa Johnsone1164de2016-02-10 21:55:02 +0000718 /// Original source file name recorded in a bitcode record.
719 std::string SourceFileName;
720
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000721 /// The string identifier given to this module by the client, normally the
722 /// path to the bitcode file.
723 StringRef ModulePath;
724
725 /// For per-module summary indexes, the unique numerical identifier given to
726 /// this module by the client.
727 unsigned ModuleId;
728
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000729public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000730 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000731 ModuleSummaryIndex &TheIndex,
732 StringRef ModulePath, unsigned ModuleId);
Teresa Johnson403a7872015-10-04 14:33:43 +0000733
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000734 Error parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000735
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000736private:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000737 void setValueGUID(uint64_t ValueID, StringRef ValueName,
738 GlobalValue::LinkageTypes Linkage,
739 StringRef SourceFileName);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000740 Error parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000741 uint64_t Offset,
742 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000743 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
744 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
745 bool IsOldProfileFormat,
746 bool HasProfile);
Peter Collingbournedbd2fed2017-06-15 17:26:13 +0000747 Error parseEntireSummary(unsigned ID);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000748 Error parseModuleStringTable();
Eugene Zelenko1804a772016-08-25 00:45:04 +0000749
Peter Collingbourne9667b912017-05-04 18:03:25 +0000750 std::pair<ValueInfo, GlobalValue::GUID>
751 getValueInfoFromValueId(unsigned ValueId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000752
Peter Collingbourne5aa56d22017-06-14 22:35:27 +0000753 ModuleSummaryIndex::ModuleInfo *addThisModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000754};
Eugene Zelenko1804a772016-08-25 00:45:04 +0000755
Peter Collingbournecd513a42016-11-11 19:50:24 +0000756} // end anonymous namespace
757
758std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
759 Error Err) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000760 if (Err) {
761 std::error_code EC;
762 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
763 EC = EIB.convertToErrorCode();
764 Ctx.emitError(EIB.message());
765 });
766 return EC;
767 }
768 return std::error_code();
769}
770
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000771BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne7a748032016-11-16 21:44:45 +0000772 StringRef ProducerIdentification,
773 LLVMContext &Context)
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000774 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
Mehdi Aminief27db82016-12-12 19:34:26 +0000775 ValueList(Context) {
Peter Collingbourne7a748032016-11-16 21:44:45 +0000776 this->ProducerIdentification = ProducerIdentification;
777}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000778
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000779Error BitcodeReader::materializeForwardReferencedFunctions() {
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000780 if (WillMaterializeAllForwardRefs)
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000781 return Error::success();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000782
783 // Prevent recursion.
784 WillMaterializeAllForwardRefs = true;
785
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000786 while (!BasicBlockFwdRefQueue.empty()) {
787 Function *F = BasicBlockFwdRefQueue.front();
788 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000789 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000790 if (!BasicBlockFwdRefs.count(F))
791 // Already materialized.
792 continue;
793
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000794 // Check for a function that isn't materializable to prevent an infinite
795 // loop. When parsing a blockaddress stored in a global variable, there
796 // isn't a trivial way to check if a function will have a body without a
797 // linear search through FunctionsWithBodies, so just check it here.
798 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000799 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000800
801 // Try to materialize F.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000802 if (Error Err = materialize(F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000803 return Err;
Rafael Espindolab7993462012-01-02 07:49:53 +0000804 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000805 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000806
807 // Reset state.
808 WillMaterializeAllForwardRefs = false;
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000809 return Error::success();
Rafael Espindolab7993462012-01-02 07:49:53 +0000810}
811
Chris Lattnerfee5a372007-05-04 03:30:17 +0000812//===----------------------------------------------------------------------===//
813// Helper functions to implement forward reference resolution, etc.
814//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000815
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000816static bool hasImplicitComdat(size_t Val) {
817 switch (Val) {
818 default:
819 return false;
820 case 1: // Old WeakAnyLinkage
821 case 4: // Old LinkOnceAnyLinkage
822 case 10: // Old WeakODRLinkage
823 case 11: // Old LinkOnceODRLinkage
824 return true;
825 }
826}
827
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000828static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000829 switch (Val) {
830 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000831 case 0:
832 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000833 case 2:
834 return GlobalValue::AppendingLinkage;
835 case 3:
836 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000837 case 5:
838 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
839 case 6:
840 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
841 case 7:
842 return GlobalValue::ExternalWeakLinkage;
843 case 8:
844 return GlobalValue::CommonLinkage;
845 case 9:
846 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000847 case 12:
848 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000849 case 13:
850 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
851 case 14:
852 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000853 case 15:
854 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000855 case 1: // Old value with implicit comdat.
856 case 16:
857 return GlobalValue::WeakAnyLinkage;
858 case 10: // Old value with implicit comdat.
859 case 17:
860 return GlobalValue::WeakODRLinkage;
861 case 4: // Old value with implicit comdat.
862 case 18:
863 return GlobalValue::LinkOnceAnyLinkage;
864 case 11: // Old value with implicit comdat.
865 case 19:
866 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000867 }
868}
869
Charles Saternos75da10d2017-08-04 16:00:58 +0000870static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
871 FunctionSummary::FFlags Flags;
872 Flags.ReadNone = RawFlags & 0x1;
873 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
874 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
875 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
876 return Flags;
877}
878
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000879/// Decode the flags for GlobalValue in the summary.
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000880static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
881 uint64_t Version) {
882 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
883 // like getDecodedLinkage() above. Any future change to the linkage enum and
884 // to getDecodedLinkage() will need to be taken into account here as above.
885 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Amini1380edf2017-02-03 07:41:43 +0000886 RawFlags = RawFlags >> 4;
887 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000888 // The Live flag wasn't introduced until version 3. For dead stripping
Teresa Johnson6c475a72017-01-05 21:34:18 +0000889 // to work correctly on earlier versions, we must conservatively treat all
890 // values as live.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000891 bool Live = (RawFlags & 0x2) || Version < 3;
892 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000893}
894
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000895static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000896 switch (Val) {
897 default: // Map unknown visibilities to default.
898 case 0: return GlobalValue::DefaultVisibility;
899 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000900 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000901 }
902}
903
Nico Rieck7157bb72014-01-14 15:22:47 +0000904static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000905getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000906 switch (Val) {
907 default: // Map unknown values to default.
908 case 0: return GlobalValue::DefaultStorageClass;
909 case 1: return GlobalValue::DLLImportStorageClass;
910 case 2: return GlobalValue::DLLExportStorageClass;
911 }
912}
913
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000914static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000915 switch (Val) {
916 case 0: return GlobalVariable::NotThreadLocal;
917 default: // Map unknown non-zero value to general dynamic.
918 case 1: return GlobalVariable::GeneralDynamicTLSModel;
919 case 2: return GlobalVariable::LocalDynamicTLSModel;
920 case 3: return GlobalVariable::InitialExecTLSModel;
921 case 4: return GlobalVariable::LocalExecTLSModel;
922 }
923}
924
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000925static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
926 switch (Val) {
927 default: // Map unknown to UnnamedAddr::None.
928 case 0: return GlobalVariable::UnnamedAddr::None;
929 case 1: return GlobalVariable::UnnamedAddr::Global;
930 case 2: return GlobalVariable::UnnamedAddr::Local;
931 }
932}
933
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000934static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000935 switch (Val) {
936 default: return -1;
937 case bitc::CAST_TRUNC : return Instruction::Trunc;
938 case bitc::CAST_ZEXT : return Instruction::ZExt;
939 case bitc::CAST_SEXT : return Instruction::SExt;
940 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
941 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
942 case bitc::CAST_UITOFP : return Instruction::UIToFP;
943 case bitc::CAST_SITOFP : return Instruction::SIToFP;
944 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
945 case bitc::CAST_FPEXT : return Instruction::FPExt;
946 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
947 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
948 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000949 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000950 }
951}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000952
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000953static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000954 bool IsFP = Ty->isFPOrFPVectorTy();
955 // BinOps are only valid for int/fp or vector of int/fp types
956 if (!IsFP && !Ty->isIntOrIntVectorTy())
957 return -1;
958
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000959 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000960 default:
961 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000962 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000963 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000964 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000965 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000966 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000967 return IsFP ? Instruction::FMul : Instruction::Mul;
968 case bitc::BINOP_UDIV:
969 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000970 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000971 return IsFP ? Instruction::FDiv : Instruction::SDiv;
972 case bitc::BINOP_UREM:
973 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000974 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000975 return IsFP ? Instruction::FRem : Instruction::SRem;
976 case bitc::BINOP_SHL:
977 return IsFP ? -1 : Instruction::Shl;
978 case bitc::BINOP_LSHR:
979 return IsFP ? -1 : Instruction::LShr;
980 case bitc::BINOP_ASHR:
981 return IsFP ? -1 : Instruction::AShr;
982 case bitc::BINOP_AND:
983 return IsFP ? -1 : Instruction::And;
984 case bitc::BINOP_OR:
985 return IsFP ? -1 : Instruction::Or;
986 case bitc::BINOP_XOR:
987 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000988 }
989}
990
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000991static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000992 switch (Val) {
993 default: return AtomicRMWInst::BAD_BINOP;
994 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
995 case bitc::RMW_ADD: return AtomicRMWInst::Add;
996 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
997 case bitc::RMW_AND: return AtomicRMWInst::And;
998 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
999 case bitc::RMW_OR: return AtomicRMWInst::Or;
1000 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1001 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1002 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1003 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1004 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1005 }
1006}
1007
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001008static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001009 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +00001010 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1011 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1012 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1013 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1014 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1015 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001016 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +00001017 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001018 }
1019}
1020
David Majnemerdad0a642014-06-27 18:19:56 +00001021static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1022 switch (Val) {
1023 default: // Map unknown selection kinds to any.
1024 case bitc::COMDAT_SELECTION_KIND_ANY:
1025 return Comdat::Any;
1026 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1027 return Comdat::ExactMatch;
1028 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1029 return Comdat::Largest;
1030 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1031 return Comdat::NoDuplicates;
1032 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1033 return Comdat::SameSize;
1034 }
1035}
1036
James Molloy88eb5352015-07-10 12:52:00 +00001037static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1038 FastMathFlags FMF;
1039 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
1040 FMF.setUnsafeAlgebra();
1041 if (0 != (Val & FastMathFlags::NoNaNs))
1042 FMF.setNoNaNs();
1043 if (0 != (Val & FastMathFlags::NoInfs))
1044 FMF.setNoInfs();
1045 if (0 != (Val & FastMathFlags::NoSignedZeros))
1046 FMF.setNoSignedZeros();
1047 if (0 != (Val & FastMathFlags::AllowReciprocal))
1048 FMF.setAllowReciprocal();
Adam Nemetcd847a82017-03-28 20:11:52 +00001049 if (0 != (Val & FastMathFlags::AllowContract))
1050 FMF.setAllowContract(true);
James Molloy88eb5352015-07-10 12:52:00 +00001051 return FMF;
1052}
1053
Eugene Zelenko1804a772016-08-25 00:45:04 +00001054static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001055 switch (Val) {
1056 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1057 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1058 }
1059}
1060
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001061Type *BitcodeReader::getTypeByID(unsigned ID) {
1062 // The type table size is always specified correctly.
1063 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001064 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001065
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001066 if (Type *Ty = TypeList[ID])
1067 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001068
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001069 // If we have a forward reference, the only possible case is when it is to a
1070 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001071 return TypeList[ID] = createIdentifiedStructType(Context);
1072}
1073
1074StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1075 StringRef Name) {
1076 auto *Ret = StructType::create(Context, Name);
1077 IdentifiedStructTypes.push_back(Ret);
1078 return Ret;
1079}
1080
1081StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1082 auto *Ret = StructType::create(Context);
1083 IdentifiedStructTypes.push_back(Ret);
1084 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001085}
1086
Chris Lattnerfee5a372007-05-04 03:30:17 +00001087//===----------------------------------------------------------------------===//
1088// Functions for parsing blocks from the bitcode file
1089//===----------------------------------------------------------------------===//
1090
Amaury Sechet74084c42016-11-06 07:48:46 +00001091static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1092 switch (Val) {
1093 case Attribute::EndAttrKinds:
1094 llvm_unreachable("Synthetic enumerators which should never get here");
1095
1096 case Attribute::None: return 0;
1097 case Attribute::ZExt: return 1 << 0;
1098 case Attribute::SExt: return 1 << 1;
1099 case Attribute::NoReturn: return 1 << 2;
1100 case Attribute::InReg: return 1 << 3;
1101 case Attribute::StructRet: return 1 << 4;
1102 case Attribute::NoUnwind: return 1 << 5;
1103 case Attribute::NoAlias: return 1 << 6;
1104 case Attribute::ByVal: return 1 << 7;
1105 case Attribute::Nest: return 1 << 8;
1106 case Attribute::ReadNone: return 1 << 9;
1107 case Attribute::ReadOnly: return 1 << 10;
1108 case Attribute::NoInline: return 1 << 11;
1109 case Attribute::AlwaysInline: return 1 << 12;
1110 case Attribute::OptimizeForSize: return 1 << 13;
1111 case Attribute::StackProtect: return 1 << 14;
1112 case Attribute::StackProtectReq: return 1 << 15;
1113 case Attribute::Alignment: return 31 << 16;
1114 case Attribute::NoCapture: return 1 << 21;
1115 case Attribute::NoRedZone: return 1 << 22;
1116 case Attribute::NoImplicitFloat: return 1 << 23;
1117 case Attribute::Naked: return 1 << 24;
1118 case Attribute::InlineHint: return 1 << 25;
1119 case Attribute::StackAlignment: return 7 << 26;
1120 case Attribute::ReturnsTwice: return 1 << 29;
1121 case Attribute::UWTable: return 1 << 30;
1122 case Attribute::NonLazyBind: return 1U << 31;
1123 case Attribute::SanitizeAddress: return 1ULL << 32;
1124 case Attribute::MinSize: return 1ULL << 33;
1125 case Attribute::NoDuplicate: return 1ULL << 34;
1126 case Attribute::StackProtectStrong: return 1ULL << 35;
1127 case Attribute::SanitizeThread: return 1ULL << 36;
1128 case Attribute::SanitizeMemory: return 1ULL << 37;
1129 case Attribute::NoBuiltin: return 1ULL << 38;
1130 case Attribute::Returned: return 1ULL << 39;
1131 case Attribute::Cold: return 1ULL << 40;
1132 case Attribute::Builtin: return 1ULL << 41;
1133 case Attribute::OptimizeNone: return 1ULL << 42;
1134 case Attribute::InAlloca: return 1ULL << 43;
1135 case Attribute::NonNull: return 1ULL << 44;
1136 case Attribute::JumpTable: return 1ULL << 45;
1137 case Attribute::Convergent: return 1ULL << 46;
1138 case Attribute::SafeStack: return 1ULL << 47;
1139 case Attribute::NoRecurse: return 1ULL << 48;
1140 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1141 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1142 case Attribute::SwiftSelf: return 1ULL << 51;
1143 case Attribute::SwiftError: return 1ULL << 52;
1144 case Attribute::WriteOnly: return 1ULL << 53;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001145 case Attribute::Speculatable: return 1ULL << 54;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001146 case Attribute::StrictFP: return 1ULL << 55;
Amaury Sechet74084c42016-11-06 07:48:46 +00001147 case Attribute::Dereferenceable:
1148 llvm_unreachable("dereferenceable attribute not supported in raw format");
1149 break;
1150 case Attribute::DereferenceableOrNull:
1151 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1152 "format");
1153 break;
1154 case Attribute::ArgMemOnly:
1155 llvm_unreachable("argmemonly attribute not supported in raw format");
1156 break;
1157 case Attribute::AllocSize:
1158 llvm_unreachable("allocsize not supported in raw format");
1159 break;
1160 }
1161 llvm_unreachable("Unsupported attribute type");
1162}
1163
1164static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1165 if (!Val) return;
1166
1167 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1168 I = Attribute::AttrKind(I + 1)) {
1169 if (I == Attribute::Dereferenceable ||
1170 I == Attribute::DereferenceableOrNull ||
1171 I == Attribute::ArgMemOnly ||
1172 I == Attribute::AllocSize)
1173 continue;
1174 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1175 if (I == Attribute::Alignment)
1176 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1177 else if (I == Attribute::StackAlignment)
1178 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1179 else
1180 B.addAttribute(I);
1181 }
1182 }
1183}
1184
Bill Wendling56aeccc2013-02-04 23:32:23 +00001185/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1186/// been decoded from the given integer. This function must stay in sync with
1187/// 'encodeLLVMAttributesForBitcode'.
1188static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1189 uint64_t EncodedAttrs) {
1190 // FIXME: Remove in 4.0.
1191
1192 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1193 // the bits above 31 down by 11 bits.
1194 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1195 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1196 "Alignment must be a power of two.");
1197
1198 if (Alignment)
1199 B.addAlignmentAttr(Alignment);
Amaury Sechet74084c42016-11-06 07:48:46 +00001200 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1201 (EncodedAttrs & 0xffff));
Bill Wendling56aeccc2013-02-04 23:32:23 +00001202}
1203
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001204Error BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001205 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001206 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001207
Devang Patela05633e2008-09-26 22:53:05 +00001208 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001209 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001210
Chris Lattnerfee5a372007-05-04 03:30:17 +00001211 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001212
Reid Klecknerb5180542017-03-21 16:57:19 +00001213 SmallVector<AttributeList, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001214
Chris Lattnerfee5a372007-05-04 03:30:17 +00001215 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001216 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001217 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001218
Chris Lattner27d38752013-01-20 02:13:19 +00001219 switch (Entry.Kind) {
1220 case BitstreamEntry::SubBlock: // Handled for us already.
1221 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001222 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001223 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001224 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001225 case BitstreamEntry::Record:
1226 // The interesting case.
1227 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001228 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001229
Chris Lattnerfee5a372007-05-04 03:30:17 +00001230 // Read a record.
1231 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001232 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001233 default: // Default behavior: ignore.
1234 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00001235 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
Bill Wendling56aeccc2013-02-04 23:32:23 +00001236 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001237 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001238 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001239
Chris Lattnerfee5a372007-05-04 03:30:17 +00001240 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001241 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001242 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Reid Klecknerb5180542017-03-21 16:57:19 +00001243 Attrs.push_back(AttributeList::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001244 }
Devang Patela05633e2008-09-26 22:53:05 +00001245
Reid Klecknerb5180542017-03-21 16:57:19 +00001246 MAttributes.push_back(AttributeList::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001247 Attrs.clear();
1248 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00001249 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
Bill Wendling0dc08912013-02-12 08:13:50 +00001250 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1251 Attrs.push_back(MAttributeGroups[Record[i]]);
1252
Reid Klecknerb5180542017-03-21 16:57:19 +00001253 MAttributes.push_back(AttributeList::get(Context, Attrs));
Bill Wendling0dc08912013-02-12 08:13:50 +00001254 Attrs.clear();
1255 break;
1256 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001257 }
1258}
1259
Reid Klecknere9f36af2013-11-12 01:31:00 +00001260// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001261static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001262 switch (Code) {
1263 default:
1264 return Attribute::None;
1265 case bitc::ATTR_KIND_ALIGNMENT:
1266 return Attribute::Alignment;
1267 case bitc::ATTR_KIND_ALWAYS_INLINE:
1268 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001269 case bitc::ATTR_KIND_ARGMEMONLY:
1270 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001271 case bitc::ATTR_KIND_BUILTIN:
1272 return Attribute::Builtin;
1273 case bitc::ATTR_KIND_BY_VAL:
1274 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001275 case bitc::ATTR_KIND_IN_ALLOCA:
1276 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001277 case bitc::ATTR_KIND_COLD:
1278 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001279 case bitc::ATTR_KIND_CONVERGENT:
1280 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001281 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1282 return Attribute::InaccessibleMemOnly;
1283 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1284 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001285 case bitc::ATTR_KIND_INLINE_HINT:
1286 return Attribute::InlineHint;
1287 case bitc::ATTR_KIND_IN_REG:
1288 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001289 case bitc::ATTR_KIND_JUMP_TABLE:
1290 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001291 case bitc::ATTR_KIND_MIN_SIZE:
1292 return Attribute::MinSize;
1293 case bitc::ATTR_KIND_NAKED:
1294 return Attribute::Naked;
1295 case bitc::ATTR_KIND_NEST:
1296 return Attribute::Nest;
1297 case bitc::ATTR_KIND_NO_ALIAS:
1298 return Attribute::NoAlias;
1299 case bitc::ATTR_KIND_NO_BUILTIN:
1300 return Attribute::NoBuiltin;
1301 case bitc::ATTR_KIND_NO_CAPTURE:
1302 return Attribute::NoCapture;
1303 case bitc::ATTR_KIND_NO_DUPLICATE:
1304 return Attribute::NoDuplicate;
1305 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1306 return Attribute::NoImplicitFloat;
1307 case bitc::ATTR_KIND_NO_INLINE:
1308 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001309 case bitc::ATTR_KIND_NO_RECURSE:
1310 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001311 case bitc::ATTR_KIND_NON_LAZY_BIND:
1312 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001313 case bitc::ATTR_KIND_NON_NULL:
1314 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001315 case bitc::ATTR_KIND_DEREFERENCEABLE:
1316 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001317 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1318 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001319 case bitc::ATTR_KIND_ALLOC_SIZE:
1320 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001321 case bitc::ATTR_KIND_NO_RED_ZONE:
1322 return Attribute::NoRedZone;
1323 case bitc::ATTR_KIND_NO_RETURN:
1324 return Attribute::NoReturn;
1325 case bitc::ATTR_KIND_NO_UNWIND:
1326 return Attribute::NoUnwind;
1327 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1328 return Attribute::OptimizeForSize;
1329 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1330 return Attribute::OptimizeNone;
1331 case bitc::ATTR_KIND_READ_NONE:
1332 return Attribute::ReadNone;
1333 case bitc::ATTR_KIND_READ_ONLY:
1334 return Attribute::ReadOnly;
1335 case bitc::ATTR_KIND_RETURNED:
1336 return Attribute::Returned;
1337 case bitc::ATTR_KIND_RETURNS_TWICE:
1338 return Attribute::ReturnsTwice;
1339 case bitc::ATTR_KIND_S_EXT:
1340 return Attribute::SExt;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001341 case bitc::ATTR_KIND_SPECULATABLE:
1342 return Attribute::Speculatable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001343 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1344 return Attribute::StackAlignment;
1345 case bitc::ATTR_KIND_STACK_PROTECT:
1346 return Attribute::StackProtect;
1347 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1348 return Attribute::StackProtectReq;
1349 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1350 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001351 case bitc::ATTR_KIND_SAFESTACK:
1352 return Attribute::SafeStack;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001353 case bitc::ATTR_KIND_STRICT_FP:
1354 return Attribute::StrictFP;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001355 case bitc::ATTR_KIND_STRUCT_RET:
1356 return Attribute::StructRet;
1357 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1358 return Attribute::SanitizeAddress;
1359 case bitc::ATTR_KIND_SANITIZE_THREAD:
1360 return Attribute::SanitizeThread;
1361 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1362 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001363 case bitc::ATTR_KIND_SWIFT_ERROR:
1364 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001365 case bitc::ATTR_KIND_SWIFT_SELF:
1366 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001367 case bitc::ATTR_KIND_UW_TABLE:
1368 return Attribute::UWTable;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001369 case bitc::ATTR_KIND_WRITEONLY:
1370 return Attribute::WriteOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001371 case bitc::ATTR_KIND_Z_EXT:
1372 return Attribute::ZExt;
1373 }
1374}
1375
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001376Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1377 unsigned &Alignment) {
JF Bastien30bf96b2015-02-22 19:32:03 +00001378 // Note: Alignment in bitcode files is incremented by 1, so that zero
1379 // can be used for default alignment.
1380 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001381 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001382 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001383 return Error::success();
JF Bastien30bf96b2015-02-22 19:32:03 +00001384}
1385
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001386Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001387 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001388 if (*Kind == Attribute::None)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001389 return error("Unknown attribute kind (" + Twine(Code) + ")");
1390 return Error::success();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001391}
1392
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001393Error BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001394 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001395 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001396
1397 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001398 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001399
1400 SmallVector<uint64_t, 64> Record;
1401
1402 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001403 while (true) {
Bill Wendlingba629332013-02-10 23:24:25 +00001404 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1405
1406 switch (Entry.Kind) {
1407 case BitstreamEntry::SubBlock: // Handled for us already.
1408 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001409 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001410 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001411 return Error::success();
Bill Wendlingba629332013-02-10 23:24:25 +00001412 case BitstreamEntry::Record:
1413 // The interesting case.
1414 break;
1415 }
1416
1417 // Read a record.
1418 Record.clear();
1419 switch (Stream.readRecord(Entry.ID, Record)) {
1420 default: // Default behavior: ignore.
1421 break;
1422 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1423 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001424 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001425
Bill Wendlinge46707e2013-02-11 22:32:29 +00001426 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001427 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1428
1429 AttrBuilder B;
1430 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1431 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001432 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001433 if (Error Err = parseAttrKind(Record[++i], &Kind))
1434 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001435
1436 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001437 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001438 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001439 if (Error Err = parseAttrKind(Record[++i], &Kind))
1440 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001441 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001442 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001443 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001444 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001445 else if (Kind == Attribute::Dereferenceable)
1446 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001447 else if (Kind == Attribute::DereferenceableOrNull)
1448 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001449 else if (Kind == Attribute::AllocSize)
1450 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001451 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001452 assert((Record[i] == 3 || Record[i] == 4) &&
1453 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001454 bool HasValue = (Record[i++] == 4);
1455 SmallString<64> KindStr;
1456 SmallString<64> ValStr;
1457
1458 while (Record[i] != 0 && i != e)
1459 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001460 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001461
1462 if (HasValue) {
1463 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001464 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001465 while (Record[i] != 0 && i != e)
1466 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001467 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001468 }
1469
1470 B.addAttribute(KindStr.str(), ValStr.str());
1471 }
1472 }
1473
Reid Klecknerb5180542017-03-21 16:57:19 +00001474 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001475 break;
1476 }
1477 }
1478 }
1479}
1480
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001481Error BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001482 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001483 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001484
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001485 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001486}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001487
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001488Error BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001489 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001490 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001491
1492 SmallVector<uint64_t, 64> Record;
1493 unsigned NumRecords = 0;
1494
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001495 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001496
Chris Lattner1314b992007-04-22 06:23:29 +00001497 // Read all the records for this type table.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001498 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001499 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001500
Chris Lattner27d38752013-01-20 02:13:19 +00001501 switch (Entry.Kind) {
1502 case BitstreamEntry::SubBlock: // Handled for us already.
1503 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001504 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001505 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001506 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001507 return error("Malformed block");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001508 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001509 case BitstreamEntry::Record:
1510 // The interesting case.
1511 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001512 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001513
Chris Lattner1314b992007-04-22 06:23:29 +00001514 // Read a record.
1515 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001516 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001517 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001518 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001519 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001520 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1521 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1522 // type list. This allows us to reserve space.
1523 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001524 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001525 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001526 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001527 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001528 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001529 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001530 case bitc::TYPE_CODE_HALF: // HALF
1531 ResultTy = Type::getHalfTy(Context);
1532 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001533 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001534 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001535 break;
1536 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001537 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001538 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001539 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001540 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001541 break;
1542 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001543 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001544 break;
1545 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001546 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001547 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001548 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001549 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001550 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001551 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001552 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001553 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001554 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1555 ResultTy = Type::getX86_MMXTy(Context);
1556 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001557 case bitc::TYPE_CODE_TOKEN: // TOKEN
1558 ResultTy = Type::getTokenTy(Context);
1559 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001560 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001561 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001562 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001563
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001564 uint64_t NumBits = Record[0];
1565 if (NumBits < IntegerType::MIN_INT_BITS ||
1566 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001567 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001568 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001569 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001570 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001571 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001572 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001573 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001574 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001575 unsigned AddressSpace = 0;
1576 if (Record.size() == 2)
1577 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001578 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001579 if (!ResultTy ||
1580 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001581 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001582 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001583 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001584 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001585 case bitc::TYPE_CODE_FUNCTION_OLD: {
1586 // FIXME: attrid is dead, remove it in LLVM 4.0
1587 // FUNCTION: [vararg, attrid, retty, paramty x N]
1588 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001589 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001590 SmallVector<Type*, 8> ArgTys;
1591 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1592 if (Type *T = getTypeByID(Record[i]))
1593 ArgTys.push_back(T);
1594 else
1595 break;
1596 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001597
Nuno Lopes561dae02012-05-23 15:19:39 +00001598 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001599 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001600 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001601
1602 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1603 break;
1604 }
Chad Rosier95898722011-11-03 00:14:01 +00001605 case bitc::TYPE_CODE_FUNCTION: {
1606 // FUNCTION: [vararg, retty, paramty x N]
1607 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001608 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001609 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001610 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001611 if (Type *T = getTypeByID(Record[i])) {
1612 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001613 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001614 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001615 }
Chad Rosier95898722011-11-03 00:14:01 +00001616 else
1617 break;
1618 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001619
Chad Rosier95898722011-11-03 00:14:01 +00001620 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001621 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001622 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001623
1624 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1625 break;
1626 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001627 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001628 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001629 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001630 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001631 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1632 if (Type *T = getTypeByID(Record[i]))
1633 EltTys.push_back(T);
1634 else
1635 break;
1636 }
1637 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001638 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001639 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001640 break;
1641 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001642 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001643 if (convertToString(Record, 0, TypeName))
1644 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001645 continue;
1646
1647 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1648 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001649 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001650
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001651 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001652 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001653
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 // Check to see if this was forward referenced, if so fill in the temp.
1655 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1656 if (Res) {
1657 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001658 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001659 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001660 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001661 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001662
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001663 SmallVector<Type*, 8> EltTys;
1664 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1665 if (Type *T = getTypeByID(Record[i]))
1666 EltTys.push_back(T);
1667 else
1668 break;
1669 }
1670 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001671 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001672 Res->setBody(EltTys, Record[0]);
1673 ResultTy = Res;
1674 break;
1675 }
1676 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1677 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001678 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679
1680 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001681 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001682
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001683 // Check to see if this was forward referenced, if so fill in the temp.
1684 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1685 if (Res) {
1686 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001687 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001688 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001689 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001690 TypeName.clear();
1691 ResultTy = Res;
1692 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001693 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001694 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1695 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001696 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001697 ResultTy = getTypeByID(Record[1]);
1698 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001699 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001700 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001701 break;
1702 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1703 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001704 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001705 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001706 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001707 ResultTy = getTypeByID(Record[1]);
1708 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001709 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001710 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711 break;
1712 }
1713
1714 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001715 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001716 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001717 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001718 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001719 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001720 TypeList[NumRecords++] = ResultTy;
1721 }
1722}
1723
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001724Error BitcodeReader::parseOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001725 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1726 return error("Invalid record");
1727
1728 if (!BundleTags.empty())
1729 return error("Invalid multiple blocks");
1730
1731 SmallVector<uint64_t, 64> Record;
1732
Eugene Zelenko1804a772016-08-25 00:45:04 +00001733 while (true) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001734 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1735
1736 switch (Entry.Kind) {
1737 case BitstreamEntry::SubBlock: // Handled for us already.
1738 case BitstreamEntry::Error:
1739 return error("Malformed block");
1740 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001741 return Error::success();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001742 case BitstreamEntry::Record:
1743 // The interesting case.
1744 break;
1745 }
1746
1747 // Tags are implicitly mapped to integers by their order.
1748
1749 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1750 return error("Invalid record");
1751
1752 // OPERAND_BUNDLE_TAG: [strchr x N]
1753 BundleTags.emplace_back();
1754 if (convertToString(Record, 0, BundleTags.back()))
1755 return error("Invalid record");
1756 Record.clear();
1757 }
1758}
1759
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001760Error BitcodeReader::parseSyncScopeNames() {
1761 if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1762 return error("Invalid record");
1763
1764 if (!SSIDs.empty())
1765 return error("Invalid multiple synchronization scope names blocks");
1766
1767 SmallVector<uint64_t, 64> Record;
1768 while (true) {
1769 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1770 switch (Entry.Kind) {
1771 case BitstreamEntry::SubBlock: // Handled for us already.
1772 case BitstreamEntry::Error:
1773 return error("Malformed block");
1774 case BitstreamEntry::EndBlock:
1775 if (SSIDs.empty())
1776 return error("Invalid empty synchronization scope names block");
1777 return Error::success();
1778 case BitstreamEntry::Record:
1779 // The interesting case.
1780 break;
1781 }
1782
1783 // Synchronization scope names are implicitly mapped to synchronization
1784 // scope IDs by their order.
1785
1786 if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1787 return error("Invalid record");
1788
1789 SmallString<16> SSN;
1790 if (convertToString(Record, 0, SSN))
1791 return error("Invalid record");
1792
1793 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1794 Record.clear();
1795 }
1796}
1797
Teresa Johnsonff642b92015-09-17 20:12:00 +00001798/// Associate a value with its name from the given index in the provided record.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001799Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1800 unsigned NameIndex, Triple &TT) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001801 SmallString<128> ValueName;
1802 if (convertToString(Record, NameIndex, ValueName))
1803 return error("Invalid record");
1804 unsigned ValueID = Record[0];
1805 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1806 return error("Invalid record");
1807 Value *V = ValueList[ValueID];
1808
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001809 StringRef NameStr(ValueName.data(), ValueName.size());
1810 if (NameStr.find_first_of(0) != StringRef::npos)
1811 return error("Invalid value name");
1812 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001813 auto *GO = dyn_cast<GlobalObject>(V);
1814 if (GO) {
1815 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1816 if (TT.isOSBinFormatMachO())
1817 GO->setComdat(nullptr);
1818 else
1819 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1820 }
1821 }
1822 return V;
1823}
1824
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001825/// Helper to note and return the current location, and jump to the given
1826/// offset.
1827static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1828 BitstreamCursor &Stream) {
1829 // Save the current parsing location so we can jump back at the end
1830 // of the VST read.
1831 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1832 Stream.JumpToBit(Offset * 32);
1833#ifndef NDEBUG
1834 // Do some checking if we are in debug mode.
1835 BitstreamEntry Entry = Stream.advance();
1836 assert(Entry.Kind == BitstreamEntry::SubBlock);
1837 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1838#else
1839 // In NDEBUG mode ignore the output so we don't get an unused variable
1840 // warning.
1841 Stream.advance();
1842#endif
1843 return CurrentBit;
1844}
1845
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001846void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1847 Function *F,
1848 ArrayRef<uint64_t> Record) {
1849 // Note that we subtract 1 here because the offset is relative to one word
1850 // before the start of the identification or module block, which was
1851 // historically always the start of the regular bitcode header.
1852 uint64_t FuncWordOffset = Record[1] - 1;
1853 uint64_t FuncBitOffset = FuncWordOffset * 32;
1854 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1855 // Set the LastFunctionBlockBit to point to the last function block.
1856 // Later when parsing is resumed after function materialization,
1857 // we can simply skip that last function block.
1858 if (FuncBitOffset > LastFunctionBlockBit)
1859 LastFunctionBlockBit = FuncBitOffset;
1860}
1861
1862/// Read a new-style GlobalValue symbol table.
1863Error BitcodeReader::parseGlobalValueSymbolTable() {
1864 unsigned FuncBitcodeOffsetDelta =
1865 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1866
1867 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1868 return error("Invalid record");
1869
1870 SmallVector<uint64_t, 64> Record;
1871 while (true) {
1872 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1873
1874 switch (Entry.Kind) {
1875 case BitstreamEntry::SubBlock:
1876 case BitstreamEntry::Error:
1877 return error("Malformed block");
1878 case BitstreamEntry::EndBlock:
1879 return Error::success();
1880 case BitstreamEntry::Record:
1881 break;
1882 }
1883
1884 Record.clear();
1885 switch (Stream.readRecord(Entry.ID, Record)) {
1886 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1887 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1888 cast<Function>(ValueList[Record[0]]), Record);
1889 break;
1890 }
1891 }
1892}
1893
Teresa Johnsonff642b92015-09-17 20:12:00 +00001894/// Parse the value symbol table at either the current parsing location or
1895/// at the given bit offset if provided.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001896Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001897 uint64_t CurrentBit;
1898 // Pass in the Offset to distinguish between calling for the module-level
1899 // VST (where we want to jump to the VST offset) and the function-level
1900 // VST (where we don't).
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001901 if (Offset > 0) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001902 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001903 // If this module uses a string table, read this as a module-level VST.
1904 if (UseStrtab) {
1905 if (Error Err = parseGlobalValueSymbolTable())
1906 return Err;
1907 Stream.JumpToBit(CurrentBit);
1908 return Error::success();
1909 }
1910 // Otherwise, the VST will be in a similar format to a function-level VST,
1911 // and will contain symbol names.
1912 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001913
1914 // Compute the delta between the bitcode indices in the VST (the word offset
1915 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1916 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1917 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1918 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1919 // just before entering the VST subblock because: 1) the EnterSubBlock
1920 // changes the AbbrevID width; 2) the VST block is nested within the same
1921 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1922 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1923 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1924 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1925 unsigned FuncBitcodeOffsetDelta =
1926 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1927
Chris Lattner982ec1e2007-05-05 00:17:00 +00001928 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001929 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001930
1931 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001932
David Majnemer3087b222015-01-20 05:58:07 +00001933 Triple TT(TheModule->getTargetTriple());
1934
Chris Lattnerccaa4482007-04-23 21:26:05 +00001935 // Read all the records for this value table.
1936 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00001937
1938 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001939 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001940
Chris Lattner27d38752013-01-20 02:13:19 +00001941 switch (Entry.Kind) {
1942 case BitstreamEntry::SubBlock: // Handled for us already.
1943 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001944 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001945 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001946 if (Offset > 0)
1947 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001948 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001949 case BitstreamEntry::Record:
1950 // The interesting case.
1951 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001952 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001953
Chris Lattnerccaa4482007-04-23 21:26:05 +00001954 // Read a record.
1955 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001956 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001957 default: // Default behavior: unknown type.
1958 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001959 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001960 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1961 if (Error Err = ValOrErr.takeError())
1962 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001963 ValOrErr.get();
1964 break;
1965 }
1966 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001967 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001968 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1969 if (Error Err = ValOrErr.takeError())
1970 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001971 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001972
Peter Collingbournedb4cafa2017-04-06 19:39:24 +00001973 // Ignore function offsets emitted for aliases of functions in older
1974 // versions of LLVM.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001975 if (auto *F = dyn_cast<Function>(V))
1976 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001977 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001978 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001979 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001980 if (convertToString(Record, 1, ValueName))
1981 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001982 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001983 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001984 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001985
Daniel Dunbard786b512009-07-26 00:34:27 +00001986 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001987 ValueName.clear();
1988 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001989 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001990 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001991 }
1992}
1993
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001994/// Decode a signed value stored with the sign bit in the LSB for dense VBR
1995/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001996uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001997 if ((V & 1) == 0)
1998 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001999 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002000 return -(V >> 1);
2001 // There is no such thing as -0 with integers. "-0" really means MININT.
2002 return 1ULL << 63;
2003}
2004
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002005/// Resolve all of the initializers for global values and aliases that we can.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002006Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Eugene Zelenko975293f2017-09-07 23:28:24 +00002007 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2008 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002009 IndirectSymbolInitWorklist;
Eugene Zelenko975293f2017-09-07 23:28:24 +00002010 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2011 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2012 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002013
Chris Lattner44c17072007-04-26 02:46:40 +00002014 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002015 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002016 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002017 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002018 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002019
2020 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002021 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002022 if (ValID >= ValueList.size()) {
2023 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002024 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002025 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002026 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002027 GlobalInitWorklist.back().first->setInitializer(C);
2028 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002029 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002030 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002031 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002032 }
2033
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002034 while (!IndirectSymbolInitWorklist.empty()) {
2035 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002036 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002037 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002038 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002039 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2040 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002041 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002042 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2043 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002044 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002045 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002046 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002047 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002048 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002049
2050 while (!FunctionPrefixWorklist.empty()) {
2051 unsigned ValID = FunctionPrefixWorklist.back().second;
2052 if (ValID >= ValueList.size()) {
2053 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2054 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002055 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002056 FunctionPrefixWorklist.back().first->setPrefixData(C);
2057 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002058 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002059 }
2060 FunctionPrefixWorklist.pop_back();
2061 }
2062
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002063 while (!FunctionPrologueWorklist.empty()) {
2064 unsigned ValID = FunctionPrologueWorklist.back().second;
2065 if (ValID >= ValueList.size()) {
2066 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2067 } else {
2068 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2069 FunctionPrologueWorklist.back().first->setPrologueData(C);
2070 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002071 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002072 }
2073 FunctionPrologueWorklist.pop_back();
2074 }
2075
David Majnemer7fddecc2015-06-17 20:52:32 +00002076 while (!FunctionPersonalityFnWorklist.empty()) {
2077 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2078 if (ValID >= ValueList.size()) {
2079 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2080 } else {
2081 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2082 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2083 else
2084 return error("Expected a constant");
2085 }
2086 FunctionPersonalityFnWorklist.pop_back();
2087 }
2088
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002089 return Error::success();
Chris Lattner44c17072007-04-26 02:46:40 +00002090}
2091
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002092static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002093 SmallVector<uint64_t, 8> Words(Vals.size());
David Majnemer2d006e72016-08-12 04:32:42 +00002094 transform(Vals, Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002095 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002096
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002097 return APInt(TypeBits, Words);
2098}
2099
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002100Error BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002101 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002102 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002103
2104 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002105
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002106 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002107 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002108 unsigned NextCstNo = ValueList.size();
Eugene Zelenko1804a772016-08-25 00:45:04 +00002109
2110 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002111 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002112
Chris Lattner27d38752013-01-20 02:13:19 +00002113 switch (Entry.Kind) {
2114 case BitstreamEntry::SubBlock: // Handled for us already.
2115 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002116 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002117 case BitstreamEntry::EndBlock:
2118 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002119 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002120
Chris Lattner27d38752013-01-20 02:13:19 +00002121 // Once all the constants have been read, go through and resolve forward
2122 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002123 ValueList.resolveConstantForwardRefs();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002124 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002125 case BitstreamEntry::Record:
2126 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002127 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002128 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002129
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002130 // Read a record.
2131 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002132 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002133 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002134 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002135 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002136 default: // Default behavior: unknown constant
2137 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002138 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002139 break;
2140 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2141 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002142 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002143 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002144 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002145 if (TypeList[Record[0]] == VoidType)
2146 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002147 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002148 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002149 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002150 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002151 break;
2152 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002153 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002154 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002155 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002156 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002157 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002158 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002159 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002160
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002161 APInt VInt =
2162 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002163 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002164
Chris Lattner08feb1e2007-04-24 04:04:35 +00002165 break;
2166 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002167 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002168 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002169 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002170 if (CurTy->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002171 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
Tim Northover29178a32013-01-22 09:46:31 +00002172 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002173 else if (CurTy->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002174 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
Tim Northover29178a32013-01-22 09:46:31 +00002175 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002176 else if (CurTy->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002177 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002178 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002179 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002180 // Bits are not stored the same way as a normal i80 APInt, compensate.
2181 uint64_t Rearrange[2];
2182 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2183 Rearrange[1] = Record[0] >> 48;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002184 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
Tim Northover29178a32013-01-22 09:46:31 +00002185 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002186 } else if (CurTy->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002187 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
Tim Northover29178a32013-01-22 09:46:31 +00002188 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002189 else if (CurTy->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002190 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002191 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002192 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002193 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002194 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002196
Chris Lattnere14cb882007-05-04 19:11:41 +00002197 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2198 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002199 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002200
Chris Lattnere14cb882007-05-04 19:11:41 +00002201 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002202 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002203
Chris Lattner229907c2011-07-18 04:54:35 +00002204 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002205 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002206 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002207 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002208 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002209 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2210 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002211 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002212 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002213 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002214 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2215 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002216 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002217 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002218 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002219 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002220 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002221 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002222 break;
2223 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002224 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002225 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2226 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002227 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002228
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002229 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002230 V = ConstantDataArray::getString(Context, Elts,
2231 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002232 break;
2233 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002234 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2235 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002236 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002237
Chris Lattner372dd1e2012-01-30 00:51:16 +00002238 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002239 if (EltTy->isIntegerTy(8)) {
2240 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2241 if (isa<VectorType>(CurTy))
2242 V = ConstantDataVector::get(Context, Elts);
2243 else
2244 V = ConstantDataArray::get(Context, Elts);
2245 } else if (EltTy->isIntegerTy(16)) {
2246 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2247 if (isa<VectorType>(CurTy))
2248 V = ConstantDataVector::get(Context, Elts);
2249 else
2250 V = ConstantDataArray::get(Context, Elts);
2251 } else if (EltTy->isIntegerTy(32)) {
2252 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2253 if (isa<VectorType>(CurTy))
2254 V = ConstantDataVector::get(Context, Elts);
2255 else
2256 V = ConstantDataArray::get(Context, Elts);
2257 } else if (EltTy->isIntegerTy(64)) {
2258 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2259 if (isa<VectorType>(CurTy))
2260 V = ConstantDataVector::get(Context, Elts);
2261 else
2262 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002263 } else if (EltTy->isHalfTy()) {
2264 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2265 if (isa<VectorType>(CurTy))
2266 V = ConstantDataVector::getFP(Context, Elts);
2267 else
2268 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002269 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002270 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002271 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002272 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002273 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002274 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002275 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002276 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002277 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002278 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002279 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002280 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002281 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002282 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002283 }
2284 break;
2285 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002286 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002287 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002288 return error("Invalid record");
2289 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002290 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002291 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002292 } else {
2293 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2294 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002295 unsigned Flags = 0;
2296 if (Record.size() >= 4) {
2297 if (Opc == Instruction::Add ||
2298 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002299 Opc == Instruction::Mul ||
2300 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002301 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2302 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2303 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2304 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002305 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002306 Opc == Instruction::UDiv ||
2307 Opc == Instruction::LShr ||
2308 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002309 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002310 Flags |= SDivOperator::IsExact;
2311 }
2312 }
2313 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002314 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002315 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002316 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002317 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002318 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002319 return error("Invalid record");
2320 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002321 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002322 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002323 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002324 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002325 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002326 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002327 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002328 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2329 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002330 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002331 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002332 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002333 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2334 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2335 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2336 // operands]
David Blaikieb9263572015-03-13 21:03:36 +00002337 unsigned OpNum = 0;
2338 Type *PointeeType = nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +00002339 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2340 Record.size() % 2)
David Blaikieb9263572015-03-13 21:03:36 +00002341 PointeeType = getTypeByID(Record[OpNum++]);
Peter Collingbourned93620b2016-11-10 22:34:55 +00002342
2343 bool InBounds = false;
2344 Optional<unsigned> InRangeIndex;
2345 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2346 uint64_t Op = Record[OpNum++];
2347 InBounds = Op & 1;
2348 InRangeIndex = Op >> 1;
2349 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2350 InBounds = true;
2351
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002352 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002353 while (OpNum != Record.size()) {
2354 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002355 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002356 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002357 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002358 }
David Blaikieb9263572015-03-13 21:03:36 +00002359
David Blaikieb9263572015-03-13 21:03:36 +00002360 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002361 PointeeType !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00002362 cast<PointerType>(Elts[0]->getType()->getScalarType())
David Blaikie4a2e73b2015-04-02 18:55:32 +00002363 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002364 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002365 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002366
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00002367 if (Elts.size() < 1)
2368 return error("Invalid gep with no operands");
2369
David Blaikie4a2e73b2015-04-02 18:55:32 +00002370 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2371 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002372 InBounds, InRangeIndex);
Chris Lattner890683d2007-04-24 18:15:21 +00002373 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002374 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002375 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002376 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002377 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002378
2379 Type *SelectorTy = Type::getInt1Ty(Context);
2380
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002381 // The selector might be an i1 or an <n x i1>
2382 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002383 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002384 if (Value *V = ValueList[Record[0]])
2385 if (SelectorTy != V->getType())
2386 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002387
2388 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2389 SelectorTy),
2390 ValueList.getConstantFwdRef(Record[1],CurTy),
2391 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002392 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002393 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002394 case bitc::CST_CODE_CE_EXTRACTELT
2395 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002396 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002397 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002398 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002399 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002400 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002401 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002402 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002403 Constant *Op1 = nullptr;
2404 if (Record.size() == 4) {
2405 Type *IdxTy = getTypeByID(Record[2]);
2406 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002407 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002408 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2409 } else // TODO: Remove with llvm 4.0
2410 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2411 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002412 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002413 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002414 break;
2415 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002416 case bitc::CST_CODE_CE_INSERTELT
2417 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002418 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002419 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002420 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002421 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2422 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2423 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002424 Constant *Op2 = nullptr;
2425 if (Record.size() == 4) {
2426 Type *IdxTy = getTypeByID(Record[2]);
2427 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002428 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002429 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2430 } else // TODO: Remove with llvm 4.0
2431 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2432 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002433 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002434 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002435 break;
2436 }
2437 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002438 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002439 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002440 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002441 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2442 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002443 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002444 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002445 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002446 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002447 break;
2448 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002449 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002450 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2451 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002452 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002453 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002454 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002455 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2456 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002457 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002458 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002459 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002460 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002461 break;
2462 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002463 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002464 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002465 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002466 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002467 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002468 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002469 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2470 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2471
Duncan Sands9dff9be2010-02-15 16:12:20 +00002472 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002473 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002474 else
Owen Anderson487375e2009-07-29 18:55:55 +00002475 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002476 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002477 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002478 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002479 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002480 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002481 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002482 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002483 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002484 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002485 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002486 unsigned AsmStrSize = Record[1];
2487 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002488 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002489 unsigned ConstStrSize = Record[2+AsmStrSize];
2490 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002491 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002492
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002493 for (unsigned i = 0; i != AsmStrSize; ++i)
2494 AsmStr += (char)Record[2+i];
2495 for (unsigned i = 0; i != ConstStrSize; ++i)
2496 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002497 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002498 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002499 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002500 break;
2501 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002502 // This version adds support for the asm dialect keywords (e.g.,
2503 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002504 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002505 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002506 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002507 std::string AsmStr, ConstrStr;
2508 bool HasSideEffects = Record[0] & 1;
2509 bool IsAlignStack = (Record[0] >> 1) & 1;
2510 unsigned AsmDialect = Record[0] >> 2;
2511 unsigned AsmStrSize = Record[1];
2512 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002513 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002514 unsigned ConstStrSize = Record[2+AsmStrSize];
2515 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002516 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002517
2518 for (unsigned i = 0; i != AsmStrSize; ++i)
2519 AsmStr += (char)Record[2+i];
2520 for (unsigned i = 0; i != ConstStrSize; ++i)
2521 ConstrStr += (char)Record[3+AsmStrSize+i];
2522 PointerType *PTy = cast<PointerType>(CurTy);
2523 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2524 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002525 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002526 break;
2527 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002528 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002529 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002530 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002531 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002532 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002533 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002534 Function *Fn =
2535 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002536 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002537 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002538
2539 // If the function is already parsed we can insert the block address right
2540 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002541 BasicBlock *BB;
2542 unsigned BBID = Record[2];
2543 if (!BBID)
2544 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002545 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002546 if (!Fn->empty()) {
2547 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002548 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002549 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002550 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002551 ++BBI;
2552 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00002553 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002554 } else {
2555 // Otherwise insert a placeholder and remember it so it can be inserted
2556 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002557 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2558 if (FwdBBs.empty())
2559 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002560 if (FwdBBs.size() < BBID + 1)
2561 FwdBBs.resize(BBID + 1);
2562 if (!FwdBBs[BBID])
2563 FwdBBs[BBID] = BasicBlock::Create(Context);
2564 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002565 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002566 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002567 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002568 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002569 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002570
David Majnemer8a1c45d2015-12-12 05:38:55 +00002571 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002572 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002573 }
2574}
Chris Lattner1314b992007-04-22 06:23:29 +00002575
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002576Error BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002577 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002578 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002579
Chad Rosierca2567b2011-12-07 21:44:12 +00002580 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002581 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00002582
2583 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002584 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002585
Chris Lattner27d38752013-01-20 02:13:19 +00002586 switch (Entry.Kind) {
2587 case BitstreamEntry::SubBlock: // Handled for us already.
2588 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002589 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002590 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002591 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002592 case BitstreamEntry::Record:
2593 // The interesting case.
2594 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002595 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002596
Chad Rosierca2567b2011-12-07 21:44:12 +00002597 // Read a use list record.
2598 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002599 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002600 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002601 default: // Default behavior: unknown type.
2602 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002603 case bitc::USELIST_CODE_BB:
2604 IsBB = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00002605 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002606 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002607 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002608 if (RecordLength < 3)
2609 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002610 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002611 unsigned ID = Record.back();
2612 Record.pop_back();
2613
2614 Value *V;
2615 if (IsBB) {
2616 assert(ID < FunctionBBs.size() && "Basic block not found");
2617 V = FunctionBBs[ID];
2618 } else
2619 V = ValueList[ID];
2620 unsigned NumUses = 0;
2621 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00002622 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002623 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002624 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002625 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002626 }
2627 if (Order.size() != Record.size() || NumUses > Record.size())
2628 // Mismatches can happen if the functions are being materialized lazily
2629 // (out-of-order), or a value has been upgraded.
2630 break;
2631
2632 V->sortUseList([&](const Use &L, const Use &R) {
2633 return Order.lookup(&L) < Order.lookup(&R);
2634 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002635 break;
2636 }
2637 }
2638 }
2639}
2640
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002641/// When we see the block for metadata, remember where it is and then skip it.
2642/// This lets us lazily deserialize the metadata.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002643Error BitcodeReader::rememberAndSkipMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002644 // Save the current stream state.
2645 uint64_t CurBit = Stream.GetCurrentBitNo();
2646 DeferredMetadataInfo.push_back(CurBit);
2647
2648 // Skip over the block for now.
2649 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002650 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002651 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002652}
2653
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00002654Error BitcodeReader::materializeMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002655 for (uint64_t BitPos : DeferredMetadataInfo) {
2656 // Move the bit stream to the saved position.
2657 Stream.JumpToBit(BitPos);
Mehdi Aminief27db82016-12-12 19:34:26 +00002658 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002659 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002660 }
Peter Collingbourne89061b22017-06-12 20:10:48 +00002661
2662 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2663 // metadata.
2664 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2665 NamedMDNode *LinkerOpts =
2666 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2667 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2668 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2669 }
2670
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002671 DeferredMetadataInfo.clear();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002672 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002673}
2674
Rafael Espindola468b8682015-04-01 14:44:59 +00002675void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002676
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002677/// When we see the block for a function body, remember where it is and then
2678/// skip it. This lets us lazily deserialize the functions.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002679Error BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002680 // Get the function we are talking about.
2681 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002682 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002683
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002684 Function *Fn = FunctionsWithBodies.back();
2685 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002686
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002687 // Save the current stream state.
2688 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00002689 assert(
2690 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2691 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002692 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002694 // Skip over the function block for now.
2695 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002696 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002697 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002698}
2699
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002700Error BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002701 // Patch the initializers for globals and aliases up.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002702 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2703 return Err;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002704 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002705 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002706
2707 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002708 for (Function &F : *TheModule) {
Adrian Prantl6825fb62017-04-18 01:21:53 +00002709 MDLoader->upgradeDebugIntrinsics(F);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002710 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002711 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00002712 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00002713 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2714 // Some types could be renamed during loading if several modules are
2715 // loaded in the same LLVMContext (LTO scenario). In this case we should
2716 // remangle intrinsics names as well.
2717 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002718 }
2719
2720 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002721 for (GlobalVariable &GV : TheModule->globals())
2722 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002723
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002724 // Force deallocation of memory for these vectors to favor the client that
2725 // want lazy deserialization.
Eugene Zelenko975293f2017-09-07 23:28:24 +00002726 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2727 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002728 IndirectSymbolInits);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002729 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002730}
2731
Teresa Johnson1493ad92015-10-10 14:18:36 +00002732/// Support for lazy parsing of function bodies. This is required if we
2733/// either have an old bitcode file without a VST forward declaration record,
2734/// or if we have an anonymous function being materialized, since anonymous
2735/// functions do not have a name and are therefore not in the VST.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002736Error BitcodeReader::rememberAndSkipFunctionBodies() {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002737 Stream.JumpToBit(NextUnreadBit);
2738
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002739 if (Stream.AtEndOfStream())
2740 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00002741
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00002742 if (!SeenFirstFunctionBody)
2743 return error("Trying to materialize functions before seeing function blocks");
2744
Teresa Johnson1493ad92015-10-10 14:18:36 +00002745 // An old bitcode file with the symbol table at the end would have
2746 // finished the parse greedily.
2747 assert(SeenValueSymbolTable);
2748
2749 SmallVector<uint64_t, 64> Record;
2750
Eugene Zelenko1804a772016-08-25 00:45:04 +00002751 while (true) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002752 BitstreamEntry Entry = Stream.advance();
2753 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002754 default:
2755 return error("Expect SubBlock");
2756 case BitstreamEntry::SubBlock:
2757 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002758 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002759 return error("Expect function block");
2760 case bitc::FUNCTION_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002761 if (Error Err = rememberAndSkipFunctionBody())
2762 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002763 NextUnreadBit = Stream.GetCurrentBitNo();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002764 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002765 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00002766 }
2767 }
2768}
2769
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002770bool BitcodeReaderBase::readBlockInfo() {
Peter Collingbourne77c89b62016-11-08 04:17:11 +00002771 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2772 if (!NewBlockInfo)
2773 return true;
2774 BlockInfo = std::move(*NewBlockInfo);
2775 return false;
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002776}
2777
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002778Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002779 // v1: [selection_kind, name]
2780 // v2: [strtab_offset, strtab_size, selection_kind]
2781 StringRef Name;
2782 std::tie(Name, Record) = readNameFromStrtab(Record);
2783
Eugene Zelenko975293f2017-09-07 23:28:24 +00002784 if (Record.empty())
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002785 return error("Invalid record");
2786 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002787 std::string OldFormatName;
2788 if (!UseStrtab) {
2789 if (Record.size() < 2)
2790 return error("Invalid record");
2791 unsigned ComdatNameSize = Record[1];
2792 OldFormatName.reserve(ComdatNameSize);
2793 for (unsigned i = 0; i != ComdatNameSize; ++i)
2794 OldFormatName += (char)Record[2 + i];
2795 Name = OldFormatName;
2796 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002797 Comdat *C = TheModule->getOrInsertComdat(Name);
2798 C->setSelectionKind(SK);
2799 ComdatList.push_back(C);
2800 return Error::success();
2801}
2802
2803Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002804 // v1: [pointer type, isconst, initid, linkage, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002805 // visibility, threadlocal, unnamed_addr, externally_initialized,
Javed Absarf3d79042017-05-11 12:28:08 +00002806 // dllstorageclass, comdat, attributes] (name in VST)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002807 // v2: [strtab_offset, strtab_size, v1]
2808 StringRef Name;
2809 std::tie(Name, Record) = readNameFromStrtab(Record);
2810
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002811 if (Record.size() < 6)
2812 return error("Invalid record");
2813 Type *Ty = getTypeByID(Record[0]);
2814 if (!Ty)
2815 return error("Invalid record");
2816 bool isConstant = Record[1] & 1;
2817 bool explicitType = Record[1] & 2;
2818 unsigned AddressSpace;
2819 if (explicitType) {
2820 AddressSpace = Record[1] >> 2;
2821 } else {
2822 if (!Ty->isPointerTy())
2823 return error("Invalid type for value");
2824 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2825 Ty = cast<PointerType>(Ty)->getElementType();
2826 }
2827
2828 uint64_t RawLinkage = Record[3];
2829 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2830 unsigned Alignment;
2831 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2832 return Err;
2833 std::string Section;
2834 if (Record[5]) {
2835 if (Record[5] - 1 >= SectionTable.size())
2836 return error("Invalid ID");
2837 Section = SectionTable[Record[5] - 1];
2838 }
2839 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2840 // Local linkage must have default visibility.
2841 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2842 // FIXME: Change to an error if non-default in 4.0.
2843 Visibility = getDecodedVisibility(Record[6]);
2844
2845 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2846 if (Record.size() > 7)
2847 TLM = getDecodedThreadLocalMode(Record[7]);
2848
2849 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2850 if (Record.size() > 8)
2851 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2852
2853 bool ExternallyInitialized = false;
2854 if (Record.size() > 9)
2855 ExternallyInitialized = Record[9];
2856
2857 GlobalVariable *NewGV =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002858 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002859 nullptr, TLM, AddressSpace, ExternallyInitialized);
2860 NewGV->setAlignment(Alignment);
2861 if (!Section.empty())
2862 NewGV->setSection(Section);
2863 NewGV->setVisibility(Visibility);
2864 NewGV->setUnnamedAddr(UnnamedAddr);
2865
2866 if (Record.size() > 10)
2867 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2868 else
2869 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2870
2871 ValueList.push_back(NewGV);
2872
2873 // Remember which value to use for the global initializer.
2874 if (unsigned InitID = Record[2])
2875 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2876
2877 if (Record.size() > 11) {
2878 if (unsigned ComdatID = Record[11]) {
2879 if (ComdatID > ComdatList.size())
2880 return error("Invalid global variable comdat ID");
2881 NewGV->setComdat(ComdatList[ComdatID - 1]);
2882 }
2883 } else if (hasImplicitComdat(RawLinkage)) {
2884 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2885 }
Javed Absarf3d79042017-05-11 12:28:08 +00002886
2887 if (Record.size() > 12) {
2888 auto AS = getAttributes(Record[12]).getFnAttributes();
2889 NewGV->setAttributes(AS);
2890 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002891 return Error::success();
2892}
2893
2894Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002895 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002896 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002897 // prefixdata] (name in VST)
2898 // v2: [strtab_offset, strtab_size, v1]
2899 StringRef Name;
2900 std::tie(Name, Record) = readNameFromStrtab(Record);
2901
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002902 if (Record.size() < 8)
2903 return error("Invalid record");
2904 Type *Ty = getTypeByID(Record[0]);
2905 if (!Ty)
2906 return error("Invalid record");
2907 if (auto *PTy = dyn_cast<PointerType>(Ty))
2908 Ty = PTy->getElementType();
2909 auto *FTy = dyn_cast<FunctionType>(Ty);
2910 if (!FTy)
2911 return error("Invalid type for value");
2912 auto CC = static_cast<CallingConv::ID>(Record[1]);
2913 if (CC & ~CallingConv::MaxID)
2914 return error("Invalid calling convention ID");
2915
2916 Function *Func =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002917 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002918
2919 Func->setCallingConv(CC);
2920 bool isProto = Record[2];
2921 uint64_t RawLinkage = Record[3];
2922 Func->setLinkage(getDecodedLinkage(RawLinkage));
2923 Func->setAttributes(getAttributes(Record[4]));
2924
2925 unsigned Alignment;
2926 if (Error Err = parseAlignmentValue(Record[5], Alignment))
2927 return Err;
2928 Func->setAlignment(Alignment);
2929 if (Record[6]) {
2930 if (Record[6] - 1 >= SectionTable.size())
2931 return error("Invalid ID");
2932 Func->setSection(SectionTable[Record[6] - 1]);
2933 }
2934 // Local linkage must have default visibility.
2935 if (!Func->hasLocalLinkage())
2936 // FIXME: Change to an error if non-default in 4.0.
2937 Func->setVisibility(getDecodedVisibility(Record[7]));
2938 if (Record.size() > 8 && Record[8]) {
2939 if (Record[8] - 1 >= GCTable.size())
2940 return error("Invalid ID");
2941 Func->setGC(GCTable[Record[8] - 1]);
2942 }
2943 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2944 if (Record.size() > 9)
2945 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2946 Func->setUnnamedAddr(UnnamedAddr);
2947 if (Record.size() > 10 && Record[10] != 0)
2948 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2949
2950 if (Record.size() > 11)
2951 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2952 else
2953 upgradeDLLImportExportLinkage(Func, RawLinkage);
2954
2955 if (Record.size() > 12) {
2956 if (unsigned ComdatID = Record[12]) {
2957 if (ComdatID > ComdatList.size())
2958 return error("Invalid function comdat ID");
2959 Func->setComdat(ComdatList[ComdatID - 1]);
2960 }
2961 } else if (hasImplicitComdat(RawLinkage)) {
2962 Func->setComdat(reinterpret_cast<Comdat *>(1));
2963 }
2964
2965 if (Record.size() > 13 && Record[13] != 0)
2966 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2967
2968 if (Record.size() > 14 && Record[14] != 0)
2969 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2970
2971 ValueList.push_back(Func);
2972
2973 // If this is a function with a body, remember the prototype we are
2974 // creating now, so that we can match up the body with them later.
2975 if (!isProto) {
2976 Func->setIsMaterializable(true);
2977 FunctionsWithBodies.push_back(Func);
2978 DeferredFunctionInfo[Func] = 0;
2979 }
2980 return Error::success();
2981}
2982
2983Error BitcodeReader::parseGlobalIndirectSymbolRecord(
2984 unsigned BitCode, ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002985 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
2986 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
2987 // dllstorageclass] (name in VST)
2988 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
2989 // visibility, dllstorageclass] (name in VST)
2990 // v2: [strtab_offset, strtab_size, v1]
2991 StringRef Name;
2992 std::tie(Name, Record) = readNameFromStrtab(Record);
2993
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002994 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
2995 if (Record.size() < (3 + (unsigned)NewRecord))
2996 return error("Invalid record");
2997 unsigned OpNum = 0;
2998 Type *Ty = getTypeByID(Record[OpNum++]);
2999 if (!Ty)
3000 return error("Invalid record");
3001
3002 unsigned AddrSpace;
3003 if (!NewRecord) {
3004 auto *PTy = dyn_cast<PointerType>(Ty);
3005 if (!PTy)
3006 return error("Invalid type for value");
3007 Ty = PTy->getElementType();
3008 AddrSpace = PTy->getAddressSpace();
3009 } else {
3010 AddrSpace = Record[OpNum++];
3011 }
3012
3013 auto Val = Record[OpNum++];
3014 auto Linkage = Record[OpNum++];
3015 GlobalIndirectSymbol *NewGA;
3016 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3017 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003018 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003019 TheModule);
3020 else
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003021 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003022 nullptr, TheModule);
3023 // Old bitcode files didn't have visibility field.
3024 // Local linkage must have default visibility.
3025 if (OpNum != Record.size()) {
3026 auto VisInd = OpNum++;
3027 if (!NewGA->hasLocalLinkage())
3028 // FIXME: Change to an error if non-default in 4.0.
3029 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3030 }
3031 if (OpNum != Record.size())
3032 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3033 else
3034 upgradeDLLImportExportLinkage(NewGA, Linkage);
3035 if (OpNum != Record.size())
3036 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3037 if (OpNum != Record.size())
3038 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3039 ValueList.push_back(NewGA);
3040 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3041 return Error::success();
3042}
3043
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003044Error BitcodeReader::parseModule(uint64_t ResumeBit,
3045 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003046 if (ResumeBit)
3047 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003048 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003049 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003050
Chris Lattner1314b992007-04-22 06:23:29 +00003051 SmallVector<uint64_t, 64> Record;
Chris Lattner1314b992007-04-22 06:23:29 +00003052
3053 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00003054 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003055 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003056
Chris Lattner27d38752013-01-20 02:13:19 +00003057 switch (Entry.Kind) {
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:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003061 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003062
Chris Lattner27d38752013-01-20 02:13:19 +00003063 case BitstreamEntry::SubBlock:
3064 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003065 default: // Skip unknown content.
3066 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003067 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003068 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003069 case bitc::BLOCKINFO_BLOCK_ID:
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003070 if (readBlockInfo())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003071 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003072 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003073 case bitc::PARAMATTR_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003074 if (Error Err = parseAttributeBlock())
3075 return Err;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003076 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003077 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003078 if (Error Err = parseAttributeGroupBlock())
3079 return Err;
Bill Wendlingba629332013-02-10 23:24:25 +00003080 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003081 case bitc::TYPE_BLOCK_ID_NEW:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003082 if (Error Err = parseTypeTable())
3083 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003084 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003085 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003086 if (!SeenValueSymbolTable) {
3087 // Either this is an old form VST without function index and an
3088 // associated VST forward declaration record (which would have caused
3089 // the VST to be jumped to and parsed before it was encountered
3090 // normally in the stream), or there were no function blocks to
3091 // trigger an earlier parsing of the VST.
3092 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003093 if (Error Err = parseValueSymbolTable())
3094 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003095 SeenValueSymbolTable = true;
3096 } else {
3097 // We must have had a VST forward declaration record, which caused
3098 // the parser to jump to and parse the VST earlier.
3099 assert(VSTOffset > 0);
3100 if (Stream.SkipBlock())
3101 return error("Invalid record");
3102 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003103 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003104 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003105 if (Error Err = parseConstants())
3106 return Err;
3107 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3108 return Err;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003109 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003110 case bitc::METADATA_BLOCK_ID:
Mehdi Aminibf2090e2016-12-12 19:23:39 +00003111 if (ShouldLazyLoadMetadata) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003112 if (Error Err = rememberAndSkipMetadata())
3113 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003114 break;
3115 }
3116 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Mehdi Aminief27db82016-12-12 19:34:26 +00003117 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003118 return Err;
Devang Patel7428d8a2009-07-22 17:43:22 +00003119 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003120 case bitc::METADATA_KIND_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003121 if (Error Err = MDLoader->parseMetadataKinds())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003122 return Err;
Teresa Johnson12545072015-11-15 02:00:09 +00003123 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003124 case bitc::FUNCTION_BLOCK_ID:
Mehdi Amini466a64e2016-08-13 23:39:14 +00003125 // If this is the first function body we've seen, reverse the
3126 // FunctionsWithBodies list.
3127 if (!SeenFirstFunctionBody) {
3128 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003129 if (Error Err = globalCleanup())
3130 return Err;
Mehdi Amini466a64e2016-08-13 23:39:14 +00003131 SeenFirstFunctionBody = true;
3132 }
3133
Teresa Johnsonff642b92015-09-17 20:12:00 +00003134 if (VSTOffset > 0) {
3135 // If we have a VST forward declaration record, make sure we
3136 // parse the VST now if we haven't already. It is needed to
3137 // set up the DeferredFunctionInfo vector for lazy reading.
3138 if (!SeenValueSymbolTable) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003139 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3140 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003141 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003142 // Fall through so that we record the NextUnreadBit below.
3143 // This is necessary in case we have an anonymous function that
3144 // is later materialized. Since it will not have a VST entry we
3145 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003146 } else {
3147 // If we have a VST forward declaration record, but have already
3148 // parsed the VST (just above, when the first function body was
3149 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003150 // materializing functions. The ResumeBit points to the
3151 // start of the last function block recorded in the
3152 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003153 if (Stream.SkipBlock())
3154 return error("Invalid record");
3155 continue;
3156 }
3157 }
3158
3159 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003160 // index in the VST, nor a VST forward declaration record, as
3161 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003162 // Build the DeferredFunctionInfo vector on the fly.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003163 if (Error Err = rememberAndSkipFunctionBody())
3164 return Err;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003165
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003166 // Suspend parsing when we reach the function bodies. Subsequent
3167 // materialization calls will resume it when necessary. If the bitcode
3168 // file is old, the symbol table will be at the end instead and will not
3169 // have been seen yet. In this case, just finish the parse now.
3170 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003171 NextUnreadBit = Stream.GetCurrentBitNo();
Mehdi Aminia71002e2016-08-14 00:01:27 +00003172 // After the VST has been parsed, we need to make sure intrinsic name
3173 // are auto-upgraded.
3174 return globalCleanup();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003175 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003176 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003177 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003178 if (Error Err = parseUseLists())
3179 return Err;
Chad Rosierca2567b2011-12-07 21:44:12 +00003180 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003181 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003182 if (Error Err = parseOperandBundleTags())
3183 return Err;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003184 break;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003185 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3186 if (Error Err = parseSyncScopeNames())
3187 return Err;
3188 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003189 }
3190 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003191
Chris Lattner27d38752013-01-20 02:13:19 +00003192 case BitstreamEntry::Record:
3193 // The interesting case.
3194 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003196
Chris Lattner1314b992007-04-22 06:23:29 +00003197 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003198 auto BitCode = Stream.readRecord(Entry.ID, Record);
3199 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003200 default: break; // Default behavior, ignore unknown content.
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003201 case bitc::MODULE_CODE_VERSION: {
3202 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3203 if (!VersionOrErr)
3204 return VersionOrErr.takeError();
3205 UseRelativeIDs = *VersionOrErr >= 1;
Chris Lattner1314b992007-04-22 06:23:29 +00003206 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003207 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003208 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003209 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003210 if (convertToString(Record, 0, S))
3211 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003212 TheModule->setTargetTriple(S);
3213 break;
3214 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003215 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003216 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003217 if (convertToString(Record, 0, S))
3218 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003219 TheModule->setDataLayout(S);
3220 break;
3221 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003222 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003223 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003224 if (convertToString(Record, 0, S))
3225 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003226 TheModule->setModuleInlineAsm(S);
3227 break;
3228 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003229 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3230 // FIXME: Remove in 4.0.
3231 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003232 if (convertToString(Record, 0, S))
3233 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003234 // Ignore value.
3235 break;
3236 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003237 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003238 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003239 if (convertToString(Record, 0, S))
3240 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003241 SectionTable.push_back(S);
3242 break;
3243 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003244 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003245 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003246 if (convertToString(Record, 0, S))
3247 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003248 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003249 break;
3250 }
Eugene Zelenko975293f2017-09-07 23:28:24 +00003251 case bitc::MODULE_CODE_COMDAT:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003252 if (Error Err = parseComdatRecord(Record))
3253 return Err;
David Majnemerdad0a642014-06-27 18:19:56 +00003254 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00003255 case bitc::MODULE_CODE_GLOBALVAR:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003256 if (Error Err = parseGlobalVarRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003257 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003258 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00003259 case bitc::MODULE_CODE_FUNCTION:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003260 if (Error Err = parseFunctionRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003261 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003262 break;
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003263 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003264 case bitc::MODULE_CODE_ALIAS:
Eugene Zelenko975293f2017-09-07 23:28:24 +00003265 case bitc::MODULE_CODE_ALIAS_OLD:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003266 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3267 return Err;
Chris Lattner44c17072007-04-26 02:46:40 +00003268 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003269 /// MODULE_CODE_VSTOFFSET: [offset]
3270 case bitc::MODULE_CODE_VSTOFFSET:
3271 if (Record.size() < 1)
3272 return error("Invalid record");
Peter Collingbournebfcf9802016-11-29 02:27:04 +00003273 // Note that we subtract 1 here because the offset is relative to one word
3274 // before the start of the identification or module block, which was
3275 // historically always the start of the regular bitcode header.
3276 VSTOffset = Record[0] - 1;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003277 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003278 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3279 case bitc::MODULE_CODE_SOURCE_FILENAME:
3280 SmallString<128> ValueName;
3281 if (convertToString(Record, 0, ValueName))
3282 return error("Invalid record");
3283 TheModule->setSourceFileName(ValueName);
3284 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003285 }
Chris Lattner1314b992007-04-22 06:23:29 +00003286 Record.clear();
3287 }
Chris Lattner1314b992007-04-22 06:23:29 +00003288}
3289
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003290Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3291 bool IsImporting) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003292 TheModule = M;
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003293 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00003294 [&](unsigned ID) { return getTypeByID(ID); });
Peter Collingbourne7a748032016-11-16 21:44:45 +00003295 return parseModule(0, ShouldLazyLoadMetadata);
Chris Lattner1314b992007-04-22 06:23:29 +00003296}
Chris Lattner6694f602007-04-29 07:54:31 +00003297
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003298Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003299 if (!isa<PointerType>(PtrType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003300 return error("Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003301 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3302
3303 if (ValType && ValType != ElemType)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003304 return error("Explicit load/store type does not match pointee "
3305 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003306 if (!PointerType::isLoadableOrStorableType(ElemType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003307 return error("Cannot load/store from pointer");
3308 return Error::success();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003309}
3310
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003311/// Lazily parse the specified function body block.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003312Error BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003313 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003314 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003315
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003316 // Unexpected unresolved metadata when parsing function.
Mehdi Aminief27db82016-12-12 19:34:26 +00003317 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003318 return error("Invalid function metadata: incoming forward references");
3319
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003320 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003321 unsigned ModuleValueListSize = ValueList.size();
Mehdi Aminief27db82016-12-12 19:34:26 +00003322 unsigned ModuleMDLoaderSize = MDLoader->size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003323
Chris Lattner85b7b402007-05-01 05:52:21 +00003324 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003325 for (Argument &I : F->args())
3326 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003327
Chris Lattner83930552007-05-01 07:01:57 +00003328 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003329 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003330 unsigned CurBBNo = 0;
3331
Chris Lattner07d09ed2010-04-03 02:17:50 +00003332 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003333 auto getLastInstruction = [&]() -> Instruction * {
3334 if (CurBB && !CurBB->empty())
3335 return &CurBB->back();
3336 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3337 !FunctionBBs[CurBBNo - 1]->empty())
3338 return &FunctionBBs[CurBBNo - 1]->back();
3339 return nullptr;
3340 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003341
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003342 std::vector<OperandBundleDef> OperandBundles;
3343
Chris Lattner85b7b402007-05-01 05:52:21 +00003344 // Read all the records.
3345 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00003346
3347 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003348 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003349
Chris Lattner27d38752013-01-20 02:13:19 +00003350 switch (Entry.Kind) {
3351 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003352 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003353 case BitstreamEntry::EndBlock:
3354 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003355
Chris Lattner27d38752013-01-20 02:13:19 +00003356 case BitstreamEntry::SubBlock:
3357 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003358 default: // Skip unknown content.
3359 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003360 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003361 break;
3362 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003363 if (Error Err = parseConstants())
3364 return Err;
Chris Lattner83930552007-05-01 07:01:57 +00003365 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003366 break;
3367 case bitc::VALUE_SYMTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003368 if (Error Err = parseValueSymbolTable())
3369 return Err;
Chris Lattner85b7b402007-05-01 05:52:21 +00003370 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003371 case bitc::METADATA_ATTACHMENT_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003372 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003373 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003374 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003375 case bitc::METADATA_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003376 assert(DeferredMetadataInfo.empty() &&
3377 "Must read all module-level metadata before function-level");
3378 if (Error Err = MDLoader->parseFunctionMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003379 return Err;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003380 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003381 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003382 if (Error Err = parseUseLists())
3383 return Err;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003384 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003385 }
3386 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003387
Chris Lattner27d38752013-01-20 02:13:19 +00003388 case BitstreamEntry::Record:
3389 // The interesting case.
3390 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003391 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003392
Chris Lattner85b7b402007-05-01 05:52:21 +00003393 // Read a record.
3394 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003395 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003396 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003397 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003398 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003399 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003400 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003401 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003402 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003403 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003404 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003405
3406 // See if anything took the address of blocks in this function.
3407 auto BBFRI = BasicBlockFwdRefs.find(F);
3408 if (BBFRI == BasicBlockFwdRefs.end()) {
3409 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3410 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3411 } else {
3412 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003413 // Check for invalid basic block references.
3414 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003415 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003416 assert(!BBRefs.empty() && "Unexpected empty array");
3417 assert(!BBRefs.front() && "Invalid reference to entry block");
3418 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3419 ++I)
3420 if (I < RE && BBRefs[I]) {
3421 BBRefs[I]->insertInto(F);
3422 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003423 } else {
3424 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3425 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003426
3427 // Erase from the table.
3428 BasicBlockFwdRefs.erase(BBFRI);
3429 }
3430
Chris Lattner83930552007-05-01 07:01:57 +00003431 CurBB = FunctionBBs[0];
3432 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003433 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003434
Chris Lattner07d09ed2010-04-03 02:17:50 +00003435 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3436 // This record indicates that the last instruction is at the same
3437 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003438 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003439
Craig Topper2617dcc2014-04-15 06:32:26 +00003440 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003441 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003442 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003443 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003444 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003445
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003446 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003447 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003448 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003449 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003450
Chris Lattner07d09ed2010-04-03 02:17:50 +00003451 unsigned Line = Record[0], Col = Record[1];
3452 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003453
Craig Topper2617dcc2014-04-15 06:32:26 +00003454 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00003455 if (ScopeID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003456 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003457 if (!Scope)
3458 return error("Invalid record");
3459 }
3460 if (IAID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003461 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003462 if (!IA)
3463 return error("Invalid record");
3464 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00003465 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3466 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003467 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003468 continue;
3469 }
3470
Chris Lattnere9759c22007-05-06 00:21:25 +00003471 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3472 unsigned OpNum = 0;
3473 Value *LHS, *RHS;
3474 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003475 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003476 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003477 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003478
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003479 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003480 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003481 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003482 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003483 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003484 if (OpNum < Record.size()) {
3485 if (Opc == Instruction::Add ||
3486 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003487 Opc == Instruction::Mul ||
3488 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003489 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003490 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003491 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003492 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003493 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003494 Opc == Instruction::UDiv ||
3495 Opc == Instruction::LShr ||
3496 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003497 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003498 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003499 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00003500 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003501 if (FMF.any())
3502 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003503 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003504
Dan Gohman1b849082009-09-07 23:54:19 +00003505 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003506 break;
3507 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003508 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3509 unsigned OpNum = 0;
3510 Value *Op;
3511 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3512 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003513 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003514
Chris Lattner229907c2011-07-18 04:54:35 +00003515 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003516 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003517 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003518 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003519 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003520 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3521 if (Temp) {
3522 InstructionList.push_back(Temp);
3523 CurBB->getInstList().push_back(Temp);
3524 }
3525 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00003526 auto CastOp = (Instruction::CastOps)Opc;
3527 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3528 return error("Invalid cast");
3529 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003530 }
Devang Patelaf206b82009-09-18 19:26:43 +00003531 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003532 break;
3533 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003534 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3535 case bitc::FUNC_CODE_INST_GEP_OLD:
3536 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003537 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003538
3539 Type *Ty;
3540 bool InBounds;
3541
3542 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3543 InBounds = Record[OpNum++];
3544 Ty = getTypeByID(Record[OpNum++]);
3545 } else {
3546 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3547 Ty = nullptr;
3548 }
3549
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003550 Value *BasePtr;
3551 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003552 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003553
David Blaikie60310f22015-05-08 00:42:26 +00003554 if (!Ty)
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003555 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003556 ->getElementType();
3557 else if (Ty !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003558 cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003559 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003560 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00003561 "Explicit gep type does not match pointee type of pointer operand");
3562
Chris Lattner5285b5e2007-05-02 05:46:45 +00003563 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003564 while (OpNum != Record.size()) {
3565 Value *Op;
3566 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003567 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003568 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003569 }
3570
David Blaikie096b1da2015-03-14 19:53:33 +00003571 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003572
Devang Patelaf206b82009-09-18 19:26:43 +00003573 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003574 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003575 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003576 break;
3577 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003578
Dan Gohman1ecaf452008-05-31 00:58:22 +00003579 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3580 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003581 unsigned OpNum = 0;
3582 Value *Agg;
3583 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003584 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003585
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003586 unsigned RecSize = Record.size();
3587 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003588 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003589
Dan Gohman1ecaf452008-05-31 00:58:22 +00003590 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003591 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003592 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003593 bool IsArray = CurTy->isArrayTy();
3594 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003595 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003596
3597 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003598 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003599 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003600 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003601 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003602 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003603 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003604 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003605 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003606
3607 if (IsStruct)
3608 CurTy = CurTy->subtypes()[Index];
3609 else
3610 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003611 }
3612
Jay Foad57aa6362011-07-13 10:26:04 +00003613 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003614 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003615 break;
3616 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003617
Dan Gohman1ecaf452008-05-31 00:58:22 +00003618 case bitc::FUNC_CODE_INST_INSERTVAL: {
3619 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003620 unsigned OpNum = 0;
3621 Value *Agg;
3622 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003623 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003624 Value *Val;
3625 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003626 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003627
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003628 unsigned RecSize = Record.size();
3629 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003630 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003631
Dan Gohman1ecaf452008-05-31 00:58:22 +00003632 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003633 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003634 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003635 bool IsArray = CurTy->isArrayTy();
3636 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003637 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003638
3639 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003640 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003641 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003642 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003643 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003644 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003645 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003646 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003647
Dan Gohman1ecaf452008-05-31 00:58:22 +00003648 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003649 if (IsStruct)
3650 CurTy = CurTy->subtypes()[Index];
3651 else
3652 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003653 }
3654
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003655 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003656 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003657
Jay Foad57aa6362011-07-13 10:26:04 +00003658 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003659 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003660 break;
3661 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003662
Chris Lattnere9759c22007-05-06 00:21:25 +00003663 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003664 // obsolete form of select
3665 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003666 unsigned OpNum = 0;
3667 Value *TrueVal, *FalseVal, *Cond;
3668 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003669 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3670 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003671 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003672
Dan Gohmanc5d28922008-09-16 01:01:33 +00003673 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003674 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003675 break;
3676 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003677
Dan Gohmanc5d28922008-09-16 01:01:33 +00003678 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3679 // new form of select
3680 // handles select i1 or select [N x i1]
3681 unsigned OpNum = 0;
3682 Value *TrueVal, *FalseVal, *Cond;
3683 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003684 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003685 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003686 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003687
3688 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003689 if (VectorType* vector_type =
3690 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003691 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003692 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003693 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003694 } else {
3695 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003696 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003697 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003698 }
3699
Gabor Greife9ecc682008-04-06 20:25:17 +00003700 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003701 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003702 break;
3703 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003704
Chris Lattner1fc27f02007-05-02 05:16:49 +00003705 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003706 unsigned OpNum = 0;
3707 Value *Vec, *Idx;
3708 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003709 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003710 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003711 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003712 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003713 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003714 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003715 break;
3716 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003717
Chris Lattner1fc27f02007-05-02 05:16:49 +00003718 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003719 unsigned OpNum = 0;
3720 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003721 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003722 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003723 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003724 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003725 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003726 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003727 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003728 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003729 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003730 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003731 break;
3732 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003733
Chris Lattnere9759c22007-05-06 00:21:25 +00003734 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3735 unsigned OpNum = 0;
3736 Value *Vec1, *Vec2, *Mask;
3737 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003738 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003739 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003740
Mon P Wang25f01062008-11-10 04:46:22 +00003741 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003742 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003743 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003744 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003745 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003746 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003747 break;
3748 }
Mon P Wang25f01062008-11-10 04:46:22 +00003749
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003750 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3751 // Old form of ICmp/FCmp returning bool
3752 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3753 // both legal on vectors but had different behaviour.
3754 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3755 // FCmp/ICmp returning bool or vector of bool
3756
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003757 unsigned OpNum = 0;
3758 Value *LHS, *RHS;
3759 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00003760 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3761 return error("Invalid record");
3762
3763 unsigned PredVal = Record[OpNum];
3764 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3765 FastMathFlags FMF;
3766 if (IsFP && Record.size() > OpNum+1)
3767 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3768
3769 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003770 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003771
Duncan Sands9dff9be2010-02-15 16:12:20 +00003772 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00003773 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003774 else
James Molloy88eb5352015-07-10 12:52:00 +00003775 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3776
3777 if (FMF.any())
3778 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00003779 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003780 break;
3781 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003782
Chris Lattnere53603e2007-05-02 04:27:25 +00003783 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003784 {
3785 unsigned Size = Record.size();
3786 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003787 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003788 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003789 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003790 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003791
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003792 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003793 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003794 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003795 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003796 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003797 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003798
Chris Lattnerf1c87102011-06-17 18:09:11 +00003799 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003800 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003801 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003802 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003803 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003804 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003805 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003806 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003807 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003808 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003809
Devang Patelaf206b82009-09-18 19:26:43 +00003810 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003811 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003812 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003813 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003814 else {
3815 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003816 Value *Cond = getValue(Record, 2, NextValueNo,
3817 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003818 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003819 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003820 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003821 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003822 }
3823 break;
3824 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00003825 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003826 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003827 return error("Invalid record");
3828 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003829 Value *CleanupPad =
3830 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003831 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00003832 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003833 BasicBlock *UnwindDest = nullptr;
3834 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00003835 UnwindDest = getBasicBlock(Record[Idx++]);
3836 if (!UnwindDest)
3837 return error("Invalid record");
3838 }
3839
David Majnemer8a1c45d2015-12-12 05:38:55 +00003840 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00003841 InstructionList.push_back(I);
3842 break;
3843 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003844 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3845 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003846 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003847 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003848 Value *CatchPad =
3849 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003850 if (!CatchPad)
3851 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003852 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00003853 if (!BB)
3854 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003855
David Majnemer8a1c45d2015-12-12 05:38:55 +00003856 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00003857 InstructionList.push_back(I);
3858 break;
3859 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003860 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3861 // We must have, at minimum, the outer scope and the number of arguments.
3862 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003863 return error("Invalid record");
3864
David Majnemer654e1302015-07-31 17:58:14 +00003865 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003866
3867 Value *ParentPad =
3868 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3869
3870 unsigned NumHandlers = Record[Idx++];
3871
3872 SmallVector<BasicBlock *, 2> Handlers;
3873 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3874 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3875 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00003876 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003877 Handlers.push_back(BB);
3878 }
3879
3880 BasicBlock *UnwindDest = nullptr;
3881 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00003882 UnwindDest = getBasicBlock(Record[Idx++]);
3883 if (!UnwindDest)
3884 return error("Invalid record");
3885 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003886
3887 if (Record.size() != Idx)
3888 return error("Invalid record");
3889
3890 auto *CatchSwitch =
3891 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3892 for (BasicBlock *Handler : Handlers)
3893 CatchSwitch->addHandler(Handler);
3894 I = CatchSwitch;
3895 InstructionList.push_back(I);
3896 break;
3897 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003898 case bitc::FUNC_CODE_INST_CATCHPAD:
3899 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3900 // We must have, at minimum, the outer scope and the number of arguments.
3901 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003902 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003903
David Majnemer654e1302015-07-31 17:58:14 +00003904 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003905
3906 Value *ParentPad =
3907 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3908
David Majnemer654e1302015-07-31 17:58:14 +00003909 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00003910
David Majnemer654e1302015-07-31 17:58:14 +00003911 SmallVector<Value *, 2> Args;
3912 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3913 Value *Val;
3914 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3915 return error("Invalid record");
3916 Args.push_back(Val);
3917 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003918
David Majnemer654e1302015-07-31 17:58:14 +00003919 if (Record.size() != Idx)
3920 return error("Invalid record");
3921
David Majnemer8a1c45d2015-12-12 05:38:55 +00003922 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3923 I = CleanupPadInst::Create(ParentPad, Args);
3924 else
3925 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003926 InstructionList.push_back(I);
3927 break;
3928 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003929 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003930 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003931 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003932 // "New" SwitchInst format with case ranges. The changes to write this
3933 // format were reverted but we still recognize bitcode that uses it.
3934 // Hopefully someday we will have support for case ranges and can use
3935 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003936
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003937 Type *OpTy = getTypeByID(Record[1]);
3938 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3939
Jan Wen Voungafaced02012-10-11 20:20:40 +00003940 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003941 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003942 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003943 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003944
3945 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003946
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003947 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3948 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003949
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003950 unsigned CurIdx = 5;
3951 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003952 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003953 unsigned NumItems = Record[CurIdx++];
3954 for (unsigned ci = 0; ci != NumItems; ++ci) {
3955 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003956
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003957 APInt Low;
3958 unsigned ActiveWords = 1;
3959 if (ValueBitWidth > 64)
3960 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003961 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003962 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003963 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003964
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003965 if (!isSingleNumber) {
3966 ActiveWords = 1;
3967 if (ValueBitWidth > 64)
3968 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003969 APInt High = readWideAPInt(
3970 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003971 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003972
3973 // FIXME: It is not clear whether values in the range should be
3974 // compared as signed or unsigned values. The partially
3975 // implemented changes that used this format in the past used
3976 // unsigned comparisons.
3977 for ( ; Low.ule(High); ++Low)
3978 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003979 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003980 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003981 }
3982 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00003983 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3984 cve = CaseVals.end(); cvi != cve; ++cvi)
3985 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003986 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003987 I = SI;
3988 break;
3989 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003990
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003991 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003992
Chris Lattner5285b5e2007-05-02 05:46:45 +00003993 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003994 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003995 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003996 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003997 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003998 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003999 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004000 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004001 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004002 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004003 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004004 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004005 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4006 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004007 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004008 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004009 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004010 }
4011 SI->addCase(CaseVal, DestBB);
4012 }
4013 I = SI;
4014 break;
4015 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004016 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004017 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004018 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004019 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004020 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004021 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004022 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004023 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004024 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004025 InstructionList.push_back(IBI);
4026 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4027 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4028 IBI->addDestination(DestBB);
4029 } else {
4030 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004031 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004032 }
4033 }
4034 I = IBI;
4035 break;
4036 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004037
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004038 case bitc::FUNC_CODE_INST_INVOKE: {
4039 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004040 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004041 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004042 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004043 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004044 unsigned CCInfo = Record[OpNum++];
4045 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4046 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004047
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004048 FunctionType *FTy = nullptr;
4049 if (CCInfo >> 13 & 1 &&
4050 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004051 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004052
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004053 Value *Callee;
4054 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004055 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004056
Chris Lattner229907c2011-07-18 04:54:35 +00004057 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004058 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004059 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004060 if (!FTy) {
4061 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4062 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004063 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004064 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004065 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004066 "callee operand");
4067 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004068 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004069
Chris Lattner5285b5e2007-05-02 05:46:45 +00004070 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004071 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004072 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4073 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004074 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004075 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004076 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004077
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004078 if (!FTy->isVarArg()) {
4079 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004080 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004081 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004082 // Read type/value pairs for varargs params.
4083 while (OpNum != Record.size()) {
4084 Value *Op;
4085 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004086 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004087 Ops.push_back(Op);
4088 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004089 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004090
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004091 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4092 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004093 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004094 cast<InvokeInst>(I)->setCallingConv(
4095 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004096 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004097 break;
4098 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004099 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4100 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004101 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004102 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004103 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004104 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004105 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004106 break;
4107 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004108 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004109 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004110 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004111 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004112 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004113 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004114 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004115 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004116 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004117 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004118
Jay Foad52131342011-03-30 11:28:46 +00004119 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004120 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004121
Chris Lattnere14cb882007-05-04 19:11:41 +00004122 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004123 Value *V;
4124 // With the new function encoding, it is possible that operands have
4125 // negative IDs (for forward references). Use a signed VBR
4126 // representation to keep the encoding small.
4127 if (UseRelativeIDs)
4128 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4129 else
4130 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004131 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004132 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004133 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004134 PN->addIncoming(V, BB);
4135 }
4136 I = PN;
4137 break;
4138 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004139
David Majnemer7fddecc2015-06-17 20:52:32 +00004140 case bitc::FUNC_CODE_INST_LANDINGPAD:
4141 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004142 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4143 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004144 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4145 if (Record.size() < 3)
4146 return error("Invalid record");
4147 } else {
4148 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4149 if (Record.size() < 4)
4150 return error("Invalid record");
4151 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004152 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004153 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004154 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004155 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4156 Value *PersFn = nullptr;
4157 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4158 return error("Invalid record");
4159
4160 if (!F->hasPersonalityFn())
4161 F->setPersonalityFn(cast<Constant>(PersFn));
4162 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4163 return error("Personality function mismatch");
4164 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004165
4166 bool IsCleanup = !!Record[Idx++];
4167 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004168 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004169 LP->setCleanup(IsCleanup);
4170 for (unsigned J = 0; J != NumClauses; ++J) {
4171 LandingPadInst::ClauseType CT =
4172 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4173 Value *Val;
4174
4175 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4176 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004177 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004178 }
4179
4180 assert((CT != LandingPadInst::Catch ||
4181 !isa<ArrayType>(Val->getType())) &&
4182 "Catch clause has a invalid type!");
4183 assert((CT != LandingPadInst::Filter ||
4184 isa<ArrayType>(Val->getType())) &&
4185 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004186 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004187 }
4188
4189 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004190 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004191 break;
4192 }
4193
Chris Lattnerf1c87102011-06-17 18:09:11 +00004194 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4195 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004196 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004197 uint64_t AlignRecord = Record[3];
4198 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004199 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004200 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4201 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4202 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004203 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004204 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004205 Type *Ty = getTypeByID(Record[0]);
4206 if ((AlignRecord & ExplicitTypeMask) == 0) {
4207 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4208 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004209 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004210 Ty = PTy->getElementType();
4211 }
4212 Type *OpTy = getTypeByID(Record[1]);
4213 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004214 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004215 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4216 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004217 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004218 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004219 return error("Invalid record");
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004220
4221 // FIXME: Make this an optional field.
4222 const DataLayout &DL = TheModule->getDataLayout();
4223 unsigned AS = DL.getAllocaAddrSpace();
4224
4225 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004226 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00004227 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004228 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004229 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004230 break;
4231 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004232 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004233 unsigned OpNum = 0;
4234 Value *Op;
4235 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004236 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004237 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004238
4239 Type *Ty = nullptr;
4240 if (OpNum + 3 == Record.size())
4241 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004242 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4243 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004244 if (!Ty)
4245 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004246
JF Bastien30bf96b2015-02-22 19:32:03 +00004247 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004248 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4249 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004250 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004251
Devang Patelaf206b82009-09-18 19:26:43 +00004252 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004253 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004254 }
Eli Friedman59b66882011-08-09 23:02:53 +00004255 case bitc::FUNC_CODE_INST_LOADATOMIC: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004256 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
Eli Friedman59b66882011-08-09 23:02:53 +00004257 unsigned OpNum = 0;
4258 Value *Op;
4259 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004260 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004261 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004262
David Blaikie85035652015-02-25 01:07:20 +00004263 Type *Ty = nullptr;
4264 if (OpNum + 5 == Record.size())
4265 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004266 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4267 return Err;
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004268 if (!Ty)
4269 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004270
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004271 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004272 if (Ordering == AtomicOrdering::NotAtomic ||
4273 Ordering == AtomicOrdering::Release ||
4274 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004275 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00004276 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004277 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004278 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004279
JF Bastien30bf96b2015-02-22 19:32:03 +00004280 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004281 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4282 return Err;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004283 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID);
David Blaikie85035652015-02-25 01:07:20 +00004284
Eli Friedman59b66882011-08-09 23:02:53 +00004285 InstructionList.push_back(I);
4286 break;
4287 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004288 case bitc::FUNC_CODE_INST_STORE:
4289 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004290 unsigned OpNum = 0;
4291 Value *Val, *Ptr;
4292 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004293 (BitCode == bitc::FUNC_CODE_INST_STORE
4294 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4295 : popValue(Record, OpNum, NextValueNo,
4296 cast<PointerType>(Ptr->getType())->getElementType(),
4297 Val)) ||
4298 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004299 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004300
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004301 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4302 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004303 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004304 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4305 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004306 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004307 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004308 break;
4309 }
David Blaikie50a06152015-04-22 04:14:46 +00004310 case bitc::FUNC_CODE_INST_STOREATOMIC:
4311 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004312 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
Eli Friedman59b66882011-08-09 23:02:53 +00004313 unsigned OpNum = 0;
4314 Value *Val, *Ptr;
4315 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00004316 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00004317 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4318 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4319 : popValue(Record, OpNum, NextValueNo,
4320 cast<PointerType>(Ptr->getType())->getElementType(),
4321 Val)) ||
4322 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004323 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004324
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004325 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4326 return Err;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004327 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004328 if (Ordering == AtomicOrdering::NotAtomic ||
4329 Ordering == AtomicOrdering::Acquire ||
4330 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004331 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004332 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00004333 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004334 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004335
JF Bastien30bf96b2015-02-22 19:32:03 +00004336 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004337 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4338 return Err;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004339 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
Eli Friedman59b66882011-08-09 23:02:53 +00004340 InstructionList.push_back(I);
4341 break;
4342 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004343 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004344 case bitc::FUNC_CODE_INST_CMPXCHG: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004345 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
Tim Northover420a2162014-06-13 14:24:07 +00004346 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004347 unsigned OpNum = 0;
4348 Value *Ptr, *Cmp, *New;
4349 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004350 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4351 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4352 : popValue(Record, OpNum, NextValueNo,
4353 cast<PointerType>(Ptr->getType())->getElementType(),
4354 Cmp)) ||
4355 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4356 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004357 return error("Invalid record");
4358 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00004359 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4360 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004361 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004362 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004363
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004364 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4365 return Err;
Tim Northovere94a5182014-03-11 10:48:52 +00004366 AtomicOrdering FailureOrdering;
4367 if (Record.size() < 7)
4368 FailureOrdering =
4369 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4370 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004371 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004372
4373 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004374 SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004375 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004376
4377 if (Record.size() < 8) {
4378 // Before weak cmpxchgs existed, the instruction simply returned the
4379 // value loaded from memory, so bitcode files from that era will be
4380 // expecting the first component of a modern cmpxchg.
4381 CurBB->getInstList().push_back(I);
4382 I = ExtractValueInst::Create(I, 0);
4383 } else {
4384 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4385 }
4386
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004387 InstructionList.push_back(I);
4388 break;
4389 }
4390 case bitc::FUNC_CODE_INST_ATOMICRMW: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004391 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004392 unsigned OpNum = 0;
4393 Value *Ptr, *Val;
4394 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00004395 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004396 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004397 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4398 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004399 return error("Invalid record");
4400 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004401 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4402 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004403 return error("Invalid record");
4404 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004405 if (Ordering == AtomicOrdering::NotAtomic ||
4406 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004407 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004408 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4409 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004410 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4411 InstructionList.push_back(I);
4412 break;
4413 }
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004414 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
Eli Friedmanfee02c62011-07-25 23:16:38 +00004415 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004416 return error("Invalid record");
4417 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00004418 if (Ordering == AtomicOrdering::NotAtomic ||
4419 Ordering == AtomicOrdering::Unordered ||
4420 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004421 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004422 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4423 I = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004424 InstructionList.push_back(I);
4425 break;
4426 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004427 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004428 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004429 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004430 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004431
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004432 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004433 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004434 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004435
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004436 FastMathFlags FMF;
4437 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4438 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4439 if (!FMF.any())
4440 return error("Fast math flags indicator set for call with no FMF");
4441 }
4442
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004443 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004444 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004445 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004446 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004447
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004448 Value *Callee;
4449 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004450 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004451
Chris Lattner229907c2011-07-18 04:54:35 +00004452 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004453 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004454 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004455 if (!FTy) {
4456 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4457 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004458 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00004459 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004460 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004461 "callee operand");
4462 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004463 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004464
Chris Lattner9f600c52007-05-03 22:04:19 +00004465 SmallVector<Value*, 16> Args;
4466 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004467 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004468 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004469 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004470 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004471 Args.push_back(getValue(Record, OpNum, NextValueNo,
4472 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004473 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004474 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004476
Chris Lattner9f600c52007-05-03 22:04:19 +00004477 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004478 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004479 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004480 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004481 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004482 while (OpNum != Record.size()) {
4483 Value *Op;
4484 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004485 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004486 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004487 }
4488 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004489
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004490 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4491 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004492 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004493 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004494 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00004495 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004496 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00004497 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004498 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00004499 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004500 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004501 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00004502 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004503 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004504 if (FMF.any()) {
4505 if (!isa<FPMathOperator>(I))
4506 return error("Fast-math-flags specified for call without "
4507 "floating-point scalar or vector return type");
4508 I->setFastMathFlags(FMF);
4509 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004510 break;
4511 }
4512 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4513 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004514 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004515 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004516 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004517 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004518 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004519 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004520 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004521 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004522 break;
4523 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004524
4525 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4526 // A call or an invoke can be optionally prefixed with some variable
4527 // number of operand bundle blocks. These blocks are read into
4528 // OperandBundles and consumed at the next call or invoke instruction.
4529
4530 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4531 return error("Invalid record");
4532
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004533 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004534
4535 unsigned OpNum = 1;
4536 while (OpNum != Record.size()) {
4537 Value *Op;
4538 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4539 return error("Invalid record");
4540 Inputs.push_back(Op);
4541 }
4542
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004543 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004544 continue;
4545 }
Chris Lattner83930552007-05-01 07:01:57 +00004546 }
4547
4548 // Add instruction to end of current BB. If there is no current BB, reject
4549 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004550 if (!CurBB) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004551 I->deleteValue();
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004552 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004553 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004554 if (!OperandBundles.empty()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004555 I->deleteValue();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004556 return error("Operand bundles found with no consumer");
4557 }
Chris Lattner83930552007-05-01 07:01:57 +00004558 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004559
Chris Lattner83930552007-05-01 07:01:57 +00004560 // If this was a terminator instruction, move to the next block.
4561 if (isa<TerminatorInst>(I)) {
4562 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004563 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004564 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004565
Chris Lattner83930552007-05-01 07:01:57 +00004566 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004567 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00004568 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004569 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004570
Chris Lattner27d38752013-01-20 02:13:19 +00004571OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004572
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004573 if (!OperandBundles.empty())
4574 return error("Operand bundles found with no consumer");
4575
Chris Lattner83930552007-05-01 07:01:57 +00004576 // Check the function list for unresolved values.
4577 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004578 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004579 // We found at least one unresolved value. Nuke them all to avoid leaks.
4580 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004581 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004582 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004583 delete A;
4584 }
4585 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004586 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004587 }
Chris Lattner83930552007-05-01 07:01:57 +00004588 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004589
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004590 // Unexpected unresolved metadata about to be dropped.
Mehdi Aminief27db82016-12-12 19:34:26 +00004591 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004592 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00004593
Chris Lattner85b7b402007-05-01 05:52:21 +00004594 // Trim the value list down to the size it was before we parsed this function.
4595 ValueList.shrinkTo(ModuleValueListSize);
Mehdi Aminief27db82016-12-12 19:34:26 +00004596 MDLoader->shrinkTo(ModuleMDLoaderSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004597 std::vector<BasicBlock*>().swap(FunctionBBs);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004598 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004599}
4600
Rafael Espindola7d712032013-11-05 17:16:08 +00004601/// Find the function body in the bitcode stream
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004602Error BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004603 Function *F,
4604 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004605 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00004606 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00004607 // didn't contain the function index in the VST, or when we have
4608 // an anonymous function which would not have a VST entry.
4609 // Assert that we have one of those two cases.
4610 assert(VSTOffset == 0 || !F->hasName());
4611 // Parse the next body in the stream and set its position in the
4612 // DeferredFunctionInfo map.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004613 if (Error Err = rememberAndSkipFunctionBodies())
4614 return Err;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004615 }
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004616 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004617}
4618
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004619SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4620 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4621 return SyncScope::ID(Val);
4622 if (Val >= SSIDs.size())
4623 return SyncScope::System; // Map unknown synchronization scopes to system.
4624 return SSIDs[Val];
4625}
4626
Chris Lattner9eeada92007-05-18 04:02:46 +00004627//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004628// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004629//===----------------------------------------------------------------------===//
4630
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004631Error BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004632 Function *F = dyn_cast<Function>(GV);
4633 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004634 if (!F || !F->isMaterializable())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004635 return Error::success();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004636
4637 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004638 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004639 // If its position is recorded as 0, its body is somewhere in the stream
4640 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004641 if (DFII->second == 0)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004642 if (Error Err = findFunctionInStream(F, DFII))
4643 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004644
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004645 // Materialize metadata before parsing any function bodies.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004646 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004647 return Err;
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004648
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004649 // Move the bit stream to the saved position of the deferred function body.
4650 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004651
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004652 if (Error Err = parseFunctionBody(F))
4653 return Err;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004654 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004655
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004656 if (StripDebugInfo)
4657 stripDebugInfo(*F);
4658
Chandler Carruth7132e002007-08-04 01:51:18 +00004659 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004660 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00004661 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4662 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004663 User *U = *UI;
4664 ++UI;
4665 if (CallInst *CI = dyn_cast<CallInst>(U))
4666 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004667 }
4668 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004669
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004670 // Update calls to the remangled intrinsics
4671 for (auto &I : RemangledIntrinsics)
4672 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4673 UI != UE;)
4674 // Don't expect any other users than call sites
4675 CallSite(*UI++).setCalledFunction(I.second);
4676
Peter Collingbourned4bff302015-11-05 22:03:56 +00004677 // Finish fn->subprogram upgrade for materialized functions.
Mehdi Aminief27db82016-12-12 19:34:26 +00004678 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
Peter Collingbourned4bff302015-11-05 22:03:56 +00004679 F->setSubprogram(SP);
4680
Mehdi Amini86623052016-12-16 19:16:29 +00004681 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4682 if (!MDLoader->isStrippingTBAA()) {
4683 for (auto &I : instructions(F)) {
4684 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4685 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4686 continue;
4687 MDLoader->setStripTBAA(true);
4688 stripTBAA(F->getParent());
4689 }
4690 }
4691
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004692 // Bring in any functions that this function forward-referenced via
4693 // blockaddresses.
4694 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004695}
4696
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004697Error BitcodeReader::materializeModule() {
4698 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004699 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004700
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004701 // Promise to materialize all forward references.
4702 WillMaterializeAllForwardRefs = true;
4703
Chris Lattner06310bf2009-06-16 05:15:21 +00004704 // Iterate over the module, deserializing any functions that are still on
4705 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004706 for (Function &F : *TheModule) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004707 if (Error Err = materialize(&F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004708 return Err;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004709 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00004710 // At this point, if there are any function bodies, parse the rest of
4711 // the bits in the module past the last function block we have recorded
4712 // through either lazy scanning or the VST.
4713 if (LastFunctionBlockBit || NextUnreadBit)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004714 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4715 ? LastFunctionBlockBit
4716 : NextUnreadBit))
4717 return Err;
Derek Schuff92ef9752012-02-29 00:07:09 +00004718
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004719 // Check that all block address forward references got resolved (as we
4720 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004721 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004722 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004723
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004724 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4725 // delete the old functions to clean up. We can't do this unless the entire
4726 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004727 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004728 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004729 for (auto *U : I.first->users()) {
4730 if (CallInst *CI = dyn_cast<CallInst>(U))
4731 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004732 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004733 if (!I.first->use_empty())
4734 I.first->replaceAllUsesWith(I.second);
4735 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004736 }
Rafael Espindola4e721212015-07-02 16:22:40 +00004737 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004738 // Do the same for remangled intrinsics
4739 for (auto &I : RemangledIntrinsics) {
4740 I.first->replaceAllUsesWith(I.second);
4741 I.first->eraseFromParent();
4742 }
4743 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00004744
Rafael Espindola79753a02015-12-18 21:18:57 +00004745 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00004746
4747 UpgradeModuleFlags(*TheModule);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004748 return Error::success();
Chris Lattner9eeada92007-05-18 04:02:46 +00004749}
4750
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004751std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4752 return IdentifiedStructTypes;
4753}
4754
Teresa Johnson26ab5772016-03-15 00:04:37 +00004755ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004756 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4757 StringRef ModulePath, unsigned ModuleId)
4758 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4759 ModulePath(ModulePath), ModuleId(ModuleId) {}
4760
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00004761ModuleSummaryIndex::ModuleInfo *
4762ModuleSummaryIndexBitcodeReader::addThisModule() {
4763 return TheIndex.addModule(ModulePath, ModuleId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004764}
Teresa Johnson403a7872015-10-04 14:33:43 +00004765
Peter Collingbourne9667b912017-05-04 18:03:25 +00004766std::pair<ValueInfo, GlobalValue::GUID>
4767ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4768 auto VGI = ValueIdToValueInfoMap[ValueId];
4769 assert(VGI.first);
4770 return VGI;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004771}
4772
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004773void ModuleSummaryIndexBitcodeReader::setValueGUID(
4774 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4775 StringRef SourceFileName) {
4776 std::string GlobalId =
4777 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4778 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4779 auto OriginalNameID = ValueGUID;
4780 if (GlobalValue::isLocalLinkage(Linkage))
4781 OriginalNameID = GlobalValue::getGUID(ValueName);
4782 if (PrintSummaryGUIDs)
4783 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4784 << ValueName << "\n";
Peter Collingbourne9667b912017-05-04 18:03:25 +00004785 ValueIdToValueInfoMap[ValueID] =
4786 std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004787}
4788
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004789// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00004790// blocks where we don't actually create global values. The parsed information
4791// is saved in the bitcode reader for use when later parsing summaries.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004792Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004793 uint64_t Offset,
4794 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004795 // With a strtab the VST is not required to parse the summary.
4796 if (UseStrtab)
4797 return Error::success();
4798
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004799 assert(Offset > 0 && "Expected non-zero VST offset");
4800 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4801
Teresa Johnson403a7872015-10-04 14:33:43 +00004802 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4803 return error("Invalid record");
4804
4805 SmallVector<uint64_t, 64> Record;
4806
4807 // Read all the records for this value table.
4808 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004809
4810 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004811 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4812
4813 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004814 case BitstreamEntry::SubBlock: // Handled for us already.
4815 case BitstreamEntry::Error:
4816 return error("Malformed block");
4817 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004818 // Done parsing VST, jump back to wherever we came from.
4819 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004820 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004821 case BitstreamEntry::Record:
4822 // The interesting case.
4823 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00004824 }
4825
4826 // Read a record.
4827 Record.clear();
4828 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004829 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4830 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004831 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4832 if (convertToString(Record, 1, ValueName))
4833 return error("Invalid record");
4834 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004835 assert(!SourceFileName.empty());
4836 auto VLI = ValueIdToLinkageMap.find(ValueID);
4837 assert(VLI != ValueIdToLinkageMap.end() &&
4838 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004839 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004840 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004841 ValueName.clear();
4842 break;
4843 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004844 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00004845 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004846 if (convertToString(Record, 2, ValueName))
4847 return error("Invalid record");
4848 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004849 assert(!SourceFileName.empty());
4850 auto VLI = ValueIdToLinkageMap.find(ValueID);
4851 assert(VLI != ValueIdToLinkageMap.end() &&
4852 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004853 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004854 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004855 ValueName.clear();
4856 break;
4857 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004858 case bitc::VST_CODE_COMBINED_ENTRY: {
4859 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4860 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00004861 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004862 // The "original name", which is the second value of the pair will be
4863 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
Peter Collingbourne9667b912017-05-04 18:03:25 +00004864 ValueIdToValueInfoMap[ValueID] =
4865 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004866 break;
4867 }
Teresa Johnson403a7872015-10-04 14:33:43 +00004868 }
4869 }
4870}
4871
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004872// Parse just the blocks needed for building the index out of the module.
4873// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00004874// from global value id to GlobalValueSummary objects.
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004875Error ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00004876 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4877 return error("Invalid record");
4878
Teresa Johnsone1164de2016-02-10 21:55:02 +00004879 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004880 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4881 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004882
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004883 // Read the index for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004884 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004885 BitstreamEntry Entry = Stream.advance();
4886
4887 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004888 case BitstreamEntry::Error:
4889 return error("Malformed block");
4890 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004891 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004892
4893 case BitstreamEntry::SubBlock:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004894 switch (Entry.ID) {
4895 default: // Skip unknown content.
4896 if (Stream.SkipBlock())
4897 return error("Invalid record");
4898 break;
4899 case bitc::BLOCKINFO_BLOCK_ID:
4900 // Need to parse these to get abbrev ids (e.g. for VST)
Peter Collingbourne939c7d92016-11-08 04:16:57 +00004901 if (readBlockInfo())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004902 return error("Malformed block");
4903 break;
4904 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004905 // Should have been parsed earlier via VSTOffset, unless there
4906 // is no summary section.
4907 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4908 !SeenGlobalValSummary) &&
4909 "Expected early VST parse via VSTOffset record");
4910 if (Stream.SkipBlock())
4911 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004912 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004913 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00004914 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004915 assert(!SeenValueSymbolTable &&
4916 "Already read VST when parsing summary block?");
Teresa Johnson620c1402016-09-20 23:07:17 +00004917 // We might not have a VST if there were no values in the
4918 // summary. An empty summary block generated when we are
4919 // performing ThinLTO compiles so we don't later invoke
4920 // the regular LTO process on them.
4921 if (VSTOffset > 0) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004922 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4923 return Err;
Teresa Johnson620c1402016-09-20 23:07:17 +00004924 SeenValueSymbolTable = true;
4925 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004926 SeenGlobalValSummary = true;
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00004927 if (Error Err = parseEntireSummary(Entry.ID))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004928 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004929 break;
4930 case bitc::MODULE_STRTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004931 if (Error Err = parseModuleStringTable())
4932 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004933 break;
4934 }
4935 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00004936
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004937 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004938 Record.clear();
4939 auto BitCode = Stream.readRecord(Entry.ID, Record);
4940 switch (BitCode) {
4941 default:
4942 break; // Default behavior, ignore unknown content.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004943 case bitc::MODULE_CODE_VERSION: {
4944 if (Error Err = parseVersionRecord(Record).takeError())
4945 return Err;
4946 break;
4947 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00004948 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004949 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004950 SmallString<128> ValueName;
4951 if (convertToString(Record, 0, ValueName))
4952 return error("Invalid record");
4953 SourceFileName = ValueName.c_str();
4954 break;
4955 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004956 /// MODULE_CODE_HASH: [5*i32]
4957 case bitc::MODULE_CODE_HASH: {
4958 if (Record.size() != 5)
4959 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00004960 auto &Hash = addThisModule()->second.second;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004961 int Pos = 0;
4962 for (auto &Val : Record) {
4963 assert(!(Val >> 32) && "Unexpected high bits set");
4964 Hash[Pos++] = Val;
4965 }
4966 break;
4967 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004968 /// MODULE_CODE_VSTOFFSET: [offset]
4969 case bitc::MODULE_CODE_VSTOFFSET:
4970 if (Record.size() < 1)
4971 return error("Invalid record");
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00004972 // Note that we subtract 1 here because the offset is relative to one
4973 // word before the start of the identification or module block, which
4974 // was historically always the start of the regular bitcode header.
4975 VSTOffset = Record[0] - 1;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004976 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004977 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
4978 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
4979 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
4980 // v2: [strtab offset, strtab size, v1]
Peter Collingbournef43e0ae2017-04-10 21:17:54 +00004981 case bitc::MODULE_CODE_GLOBALVAR:
4982 case bitc::MODULE_CODE_FUNCTION:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004983 case bitc::MODULE_CODE_ALIAS: {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004984 StringRef Name;
4985 ArrayRef<uint64_t> GVRecord;
4986 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
4987 if (GVRecord.size() <= 3)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004988 return error("Invalid record");
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004989 uint64_t RawLinkage = GVRecord[3];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004990 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004991 if (!UseStrtab) {
4992 ValueIdToLinkageMap[ValueId++] = Linkage;
4993 break;
4994 }
4995
4996 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004997 break;
4998 }
4999 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005000 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005001 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005002 }
5003 }
5004}
5005
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005006std::vector<ValueInfo>
5007ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5008 std::vector<ValueInfo> Ret;
5009 Ret.reserve(Record.size());
5010 for (uint64_t RefValueId : Record)
Peter Collingbourne9667b912017-05-04 18:03:25 +00005011 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005012 return Ret;
5013}
5014
5015std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
5016 ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
5017 std::vector<FunctionSummary::EdgeTy> Ret;
5018 Ret.reserve(Record.size());
5019 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5020 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
Peter Collingbourne9667b912017-05-04 18:03:25 +00005021 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005022 if (IsOldProfileFormat) {
5023 I += 1; // Skip old callsitecount field
5024 if (HasProfile)
5025 I += 1; // Skip old profilecount field
5026 } else if (HasProfile)
5027 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005028 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}});
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005029 }
5030 return Ret;
5031}
5032
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005033// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5034// objects in the index.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005035Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5036 if (Stream.EnterSubBlock(ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00005037 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005038 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00005039
5040 // Parse version
5041 {
5042 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5043 if (Entry.Kind != BitstreamEntry::Record)
5044 return error("Invalid Summary Block: record for version expected");
5045 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5046 return error("Invalid Summary Block: version expected");
5047 }
5048 const uint64_t Version = Record[0];
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005049 const bool IsOldProfileFormat = Version == 1;
Charles Saternos75da10d2017-08-04 16:00:58 +00005050 if (Version < 1 || Version > 4)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005051 return error("Invalid summary version " + Twine(Version) +
Charles Saternos75da10d2017-08-04 16:00:58 +00005052 ", 1, 2, 3 or 4 expected");
Mehdi Amini8fe69362016-04-24 03:18:11 +00005053 Record.clear();
5054
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005055 // Keep around the last seen summary to be used when we see an optional
5056 // "OriginalName" attachement.
5057 GlobalValueSummary *LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005058 GlobalValue::GUID LastSeenGUID = 0;
Peter Collingbournefa3175f2017-02-11 03:19:22 +00005059
5060 // We can expect to see any number of type ID information records before
5061 // each function summary records; these variables store the information
5062 // collected so far so that it can be used to create the summary object.
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005063 std::vector<GlobalValue::GUID> PendingTypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005064 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5065 PendingTypeCheckedLoadVCalls;
5066 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5067 PendingTypeCheckedLoadConstVCalls;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005068
5069 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005070 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5071
5072 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005073 case BitstreamEntry::SubBlock: // Handled for us already.
5074 case BitstreamEntry::Error:
5075 return error("Malformed block");
5076 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005077 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005078 case BitstreamEntry::Record:
5079 // The interesting case.
5080 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005081 }
5082
5083 // Read a record. The record format depends on whether this
5084 // is a per-module index or a combined index file. In the per-module
5085 // case the records contain the associated value's ID for correlation
5086 // with VST entries. In the combined index the correlation is done
5087 // via the bitcode offset of the summary records (which were saved
5088 // in the combined index VST entries). The records also contain
5089 // information used for ThinLTO renaming and importing.
5090 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005091 auto BitCode = Stream.readRecord(Entry.ID, Record);
5092 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005093 default: // Default behavior: ignore.
5094 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005095 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5096 uint64_t ValueID = Record[0];
5097 GlobalValue::GUID RefGUID = Record[1];
Peter Collingbourne9667b912017-05-04 18:03:25 +00005098 ValueIdToValueInfoMap[ValueID] =
5099 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005100 break;
5101 }
Charles Saternos75da10d2017-08-04 16:00:58 +00005102 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5103 // numrefs x valueid, n x (valueid)]
5104 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005105 // numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005106 // n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005107 case bitc::FS_PERMODULE:
5108 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005109 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005110 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005111 unsigned InstCount = Record[2];
Charles Saternos75da10d2017-08-04 16:00:58 +00005112 uint64_t RawFunFlags = 0;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005113 unsigned NumRefs = Record[3];
Charles Saternos75da10d2017-08-04 16:00:58 +00005114 int RefListStartIndex = 4;
5115 if (Version >= 4) {
5116 RawFunFlags = Record[3];
5117 NumRefs = Record[4];
5118 RefListStartIndex = 5;
5119 }
5120
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005121 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005122 // The module path string ref set in the summary must be owned by the
5123 // index's module string table. Since we don't have a module path
5124 // string table section in the per-module index, we create a single
5125 // module path string table entry with an empty (0) ID to take
5126 // ownership.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005127 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5128 assert(Record.size() >= RefListStartIndex + NumRefs &&
5129 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005130 std::vector<ValueInfo> Refs = makeRefList(
5131 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005132 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005133 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5134 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5135 IsOldProfileFormat, HasProfile);
5136 auto FS = llvm::make_unique<FunctionSummary>(
Charles Saternos75da10d2017-08-04 16:00:58 +00005137 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5138 std::move(Calls), std::move(PendingTypeTests),
5139 std::move(PendingTypeTestAssumeVCalls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005140 std::move(PendingTypeCheckedLoadVCalls),
5141 std::move(PendingTypeTestAssumeConstVCalls),
5142 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005143 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005144 PendingTypeTestAssumeVCalls.clear();
5145 PendingTypeCheckedLoadVCalls.clear();
5146 PendingTypeTestAssumeConstVCalls.clear();
5147 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005148 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005149 FS->setModulePath(addThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005150 FS->setOriginalName(VIAndOriginalGUID.second);
5151 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005152 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005153 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005154 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005155 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5156 // they expect all aliasee summaries to be available.
5157 case bitc::FS_ALIAS: {
5158 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005159 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005160 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005161 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005162 auto AS =
5163 llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005164 // The module path string ref set in the summary must be owned by the
5165 // index's module string table. Since we don't have a module path
5166 // string table section in the per-module index, we create a single
5167 // module path string table entry with an empty (0) ID to take
5168 // ownership.
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005169 AS->setModulePath(addThisModule()->first());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005170
Peter Collingbourne9667b912017-05-04 18:03:25 +00005171 GlobalValue::GUID AliaseeGUID =
5172 getValueInfoFromValueId(AliaseeID).first.getGUID();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005173 auto AliaseeInModule =
5174 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5175 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005176 return error("Alias expects aliasee summary to be parsed");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005177 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005178
Peter Collingbourne9667b912017-05-04 18:03:25 +00005179 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005180 AS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005181 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005182 break;
5183 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005184 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005185 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5186 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005187 uint64_t RawFlags = Record[1];
5188 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005189 std::vector<ValueInfo> Refs =
5190 makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5191 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005192 FS->setModulePath(addThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005193 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005194 FS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005195 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005196 break;
5197 }
Charles Saternos75da10d2017-08-04 16:00:58 +00005198 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005199 // numrefs x valueid, n x (valueid)]
Charles Saternos75da10d2017-08-04 16:00:58 +00005200 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005201 // numrefs x valueid, n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005202 case bitc::FS_COMBINED:
5203 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005204 unsigned ValueID = Record[0];
5205 uint64_t ModuleId = Record[1];
5206 uint64_t RawFlags = Record[2];
5207 unsigned InstCount = Record[3];
Charles Saternos75da10d2017-08-04 16:00:58 +00005208 uint64_t RawFunFlags = 0;
Teresa Johnson02e98332016-04-27 13:28:35 +00005209 unsigned NumRefs = Record[4];
Charles Saternos75da10d2017-08-04 16:00:58 +00005210 int RefListStartIndex = 5;
5211
5212 if (Version >= 4) {
5213 RawFunFlags = Record[4];
5214 NumRefs = Record[5];
5215 RefListStartIndex = 6;
5216 }
5217
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005218 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005219 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5220 assert(Record.size() >= RefListStartIndex + NumRefs &&
5221 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005222 std::vector<ValueInfo> Refs = makeRefList(
5223 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005224 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005225 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5226 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5227 IsOldProfileFormat, HasProfile);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005228 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005229 auto FS = llvm::make_unique<FunctionSummary>(
Charles Saternos75da10d2017-08-04 16:00:58 +00005230 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5231 std::move(Edges), std::move(PendingTypeTests),
5232 std::move(PendingTypeTestAssumeVCalls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005233 std::move(PendingTypeCheckedLoadVCalls),
5234 std::move(PendingTypeTestAssumeConstVCalls),
5235 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005236 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005237 PendingTypeTestAssumeVCalls.clear();
5238 PendingTypeCheckedLoadVCalls.clear();
5239 PendingTypeTestAssumeConstVCalls.clear();
5240 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005241 LastSeenSummary = FS.get();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005242 LastSeenGUID = VI.getGUID();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005243 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005244 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005245 break;
5246 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005247 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005248 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5249 // they expect all aliasee summaries to be available.
5250 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005251 unsigned ValueID = Record[0];
5252 uint64_t ModuleId = Record[1];
5253 uint64_t RawFlags = Record[2];
5254 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005255 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005256 auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005257 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005258 AS->setModulePath(ModuleIdMap[ModuleId]);
5259
Peter Collingbourne9667b912017-05-04 18:03:25 +00005260 auto AliaseeGUID =
5261 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
Teresa Johnson02e98332016-04-27 13:28:35 +00005262 auto AliaseeInModule =
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005263 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
Teresa Johnson02e98332016-04-27 13:28:35 +00005264 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005265 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00005266 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005267
Peter Collingbourne9667b912017-05-04 18:03:25 +00005268 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5269 LastSeenGUID = VI.getGUID();
5270 TheIndex.addGlobalValueSummary(VI, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005271 break;
5272 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005273 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005274 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005275 unsigned ValueID = Record[0];
5276 uint64_t ModuleId = Record[1];
5277 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005278 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005279 std::vector<ValueInfo> Refs =
5280 makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5281 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005282 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005283 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005284 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5285 LastSeenGUID = VI.getGUID();
5286 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005287 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005288 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005289 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5290 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5291 uint64_t OriginalName = Record[0];
5292 if (!LastSeenSummary)
5293 return error("Name attachment that does not follow a combined record");
5294 LastSeenSummary->setOriginalName(OriginalName);
Dehao Chen4a435e02017-03-14 17:33:01 +00005295 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005296 // Reset the LastSeenSummary
5297 LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005298 LastSeenGUID = 0;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005299 break;
5300 }
Eugene Zelenko975293f2017-09-07 23:28:24 +00005301 case bitc::FS_TYPE_TESTS:
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005302 assert(PendingTypeTests.empty());
5303 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5304 Record.end());
5305 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005306
5307 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005308 assert(PendingTypeTestAssumeVCalls.empty());
5309 for (unsigned I = 0; I != Record.size(); I += 2)
5310 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5311 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005312
5313 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005314 assert(PendingTypeCheckedLoadVCalls.empty());
5315 for (unsigned I = 0; I != Record.size(); I += 2)
5316 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5317 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005318
5319 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005320 PendingTypeTestAssumeConstVCalls.push_back(
5321 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5322 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005323
5324 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005325 PendingTypeCheckedLoadConstVCalls.push_back(
5326 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5327 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005328
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005329 case bitc::FS_CFI_FUNCTION_DEFS: {
5330 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5331 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005332 CfiFunctionDefs.insert(
5333 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005334 break;
5335 }
5336 case bitc::FS_CFI_FUNCTION_DECLS: {
5337 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5338 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005339 CfiFunctionDecls.insert(
5340 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005341 break;
5342 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005343 }
5344 }
5345 llvm_unreachable("Exit infinite loop");
5346}
5347
5348// Parse the module string table block into the Index.
5349// This populates the ModulePathStringTable map in the index.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005350Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005351 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5352 return error("Invalid record");
5353
5354 SmallVector<uint64_t, 64> Record;
5355
5356 SmallString<128> ModulePath;
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005357 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005358
5359 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005360 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5361
5362 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005363 case BitstreamEntry::SubBlock: // Handled for us already.
5364 case BitstreamEntry::Error:
5365 return error("Malformed block");
5366 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005367 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005368 case BitstreamEntry::Record:
5369 // The interesting case.
5370 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005371 }
5372
5373 Record.clear();
5374 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005375 default: // Default behavior: ignore.
5376 break;
5377 case bitc::MST_CODE_ENTRY: {
5378 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005379 uint64_t ModuleId = Record[0];
5380
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005381 if (convertToString(Record, 1, ModulePath))
5382 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005383
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005384 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5385 ModuleIdMap[ModuleId] = LastSeenModule->first();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005386
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005387 ModulePath.clear();
5388 break;
5389 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005390 /// MST_CODE_HASH: [5*i32]
5391 case bitc::MST_CODE_HASH: {
5392 if (Record.size() != 5)
5393 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005394 if (!LastSeenModule)
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005395 return error("Invalid hash that does not follow a module path");
5396 int Pos = 0;
5397 for (auto &Val : Record) {
5398 assert(!(Val >> 32) && "Unexpected high bits set");
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005399 LastSeenModule->second.second[Pos++] = Val;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005400 }
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005401 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5402 LastSeenModule = nullptr;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005403 break;
5404 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005405 }
5406 }
5407 llvm_unreachable("Exit infinite loop");
5408}
5409
Rafael Espindola48da4f42013-11-04 16:16:24 +00005410namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +00005411
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00005412// FIXME: This class is only here to support the transition to llvm::Error. It
5413// will be removed once this transition is complete. Clients should prefer to
5414// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00005415class BitcodeErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +00005416 const char *name() const noexcept override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00005417 return "llvm.bitcode";
5418 }
Eugene Zelenko975293f2017-09-07 23:28:24 +00005419
Craig Topper73156022014-03-02 09:09:27 +00005420 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005421 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005422 switch (E) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005423 case BitcodeError::CorruptedBitcode:
5424 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00005425 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00005426 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00005427 }
5428};
Eugene Zelenko1804a772016-08-25 00:45:04 +00005429
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00005430} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00005431
Chris Bieneman770163e2014-09-19 20:29:02 +00005432static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5433
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005434const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00005435 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005436}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005437
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005438static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5439 unsigned Block, unsigned RecordID) {
5440 if (Stream.EnterSubBlock(Block))
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005441 return error("Invalid record");
5442
5443 StringRef Strtab;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005444 while (true) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005445 BitstreamEntry Entry = Stream.advance();
5446 switch (Entry.Kind) {
5447 case BitstreamEntry::EndBlock:
5448 return Strtab;
5449
5450 case BitstreamEntry::Error:
5451 return error("Malformed block");
5452
5453 case BitstreamEntry::SubBlock:
5454 if (Stream.SkipBlock())
5455 return error("Malformed block");
5456 break;
5457
5458 case BitstreamEntry::Record:
5459 StringRef Blob;
5460 SmallVector<uint64_t, 1> Record;
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005461 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005462 Strtab = Blob;
5463 break;
5464 }
5465 }
5466}
5467
Chris Lattner6694f602007-04-29 07:54:31 +00005468//===----------------------------------------------------------------------===//
5469// External interface
5470//===----------------------------------------------------------------------===//
5471
Peter Collingbourne7a748032016-11-16 21:44:45 +00005472Expected<std::vector<BitcodeModule>>
5473llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005474 auto FOrErr = getBitcodeFileContents(Buffer);
5475 if (!FOrErr)
5476 return FOrErr.takeError();
5477 return std::move(FOrErr->Mods);
5478}
5479
5480Expected<BitcodeFileContents>
5481llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005482 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5483 if (!StreamOrErr)
5484 return StreamOrErr.takeError();
5485 BitstreamCursor &Stream = *StreamOrErr;
5486
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005487 BitcodeFileContents F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005488 while (true) {
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005489 uint64_t BCBegin = Stream.getCurrentByteNo();
5490
Peter Collingbourne7a748032016-11-16 21:44:45 +00005491 // We may be consuming bitcode from a client that leaves garbage at the end
5492 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5493 // the end that there cannot possibly be another module, stop looking.
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005494 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005495 return F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005496
5497 BitstreamEntry Entry = Stream.advance();
5498 switch (Entry.Kind) {
5499 case BitstreamEntry::EndBlock:
5500 case BitstreamEntry::Error:
5501 return error("Malformed block");
5502
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005503 case BitstreamEntry::SubBlock: {
5504 uint64_t IdentificationBit = -1ull;
5505 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5506 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5507 if (Stream.SkipBlock())
5508 return error("Malformed block");
5509
5510 Entry = Stream.advance();
5511 if (Entry.Kind != BitstreamEntry::SubBlock ||
5512 Entry.ID != bitc::MODULE_BLOCK_ID)
5513 return error("Malformed block");
5514 }
5515
5516 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5517 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5518 if (Stream.SkipBlock())
5519 return error("Malformed block");
5520
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005521 F.Mods.push_back({Stream.getBitcodeBytes().slice(
5522 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5523 Buffer.getBufferIdentifier(), IdentificationBit,
5524 ModuleBit});
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005525 continue;
5526 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005527
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005528 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005529 Expected<StringRef> Strtab =
5530 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005531 if (!Strtab)
5532 return Strtab.takeError();
5533 // This string table is used by every preceding bitcode module that does
5534 // not have its own string table. A bitcode file may have multiple
5535 // string tables if it was created by binary concatenation, for example
5536 // with "llvm-cat -b".
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005537 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005538 if (!I->Strtab.empty())
5539 break;
5540 I->Strtab = *Strtab;
5541 }
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005542 // Similarly, the string table is used by every preceding symbol table;
5543 // normally there will be just one unless the bitcode file was created
5544 // by binary concatenation.
5545 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5546 F.StrtabForSymtab = *Strtab;
5547 continue;
5548 }
5549
5550 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5551 Expected<StringRef> SymtabOrErr =
5552 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5553 if (!SymtabOrErr)
5554 return SymtabOrErr.takeError();
5555
5556 // We can expect the bitcode file to have multiple symbol tables if it
5557 // was created by binary concatenation. In that case we silently
5558 // ignore any subsequent symbol tables, which is fine because this is a
5559 // low level function. The client is expected to notice that the number
5560 // of modules in the symbol table does not match the number of modules
5561 // in the input file and regenerate the symbol table.
5562 if (F.Symtab.empty())
5563 F.Symtab = *SymtabOrErr;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005564 continue;
5565 }
5566
Peter Collingbourne7a748032016-11-16 21:44:45 +00005567 if (Stream.SkipBlock())
5568 return error("Malformed block");
5569 continue;
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005570 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005571 case BitstreamEntry::Record:
5572 Stream.skipRecord(Entry.ID);
5573 continue;
5574 }
5575 }
5576}
5577
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005578/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00005579///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005580/// This isn't always used in a lazy context. In particular, it's also used by
Peter Collingbourne7a748032016-11-16 21:44:45 +00005581/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005582/// in forward-referenced functions from block address references.
5583///
Rafael Espindola728074b2015-06-17 00:40:56 +00005584/// \param[in] MaterializeAll Set to \c true if we should materialize
5585/// everything.
Peter Collingbourne7a748032016-11-16 21:44:45 +00005586Expected<std::unique_ptr<Module>>
5587BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005588 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005589 BitstreamCursor Stream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005590
Peter Collingbourne7a748032016-11-16 21:44:45 +00005591 std::string ProducerIdentification;
5592 if (IdentificationBit != -1ull) {
5593 Stream.JumpToBit(IdentificationBit);
5594 Expected<std::string> ProducerIdentificationOrErr =
5595 readIdentificationBlock(Stream);
5596 if (!ProducerIdentificationOrErr)
5597 return ProducerIdentificationOrErr.takeError();
5598
5599 ProducerIdentification = *ProducerIdentificationOrErr;
5600 }
5601
5602 Stream.JumpToBit(ModuleBit);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005603 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5604 Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005605
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005606 std::unique_ptr<Module> M =
Peter Collingbourne7a748032016-11-16 21:44:45 +00005607 llvm::make_unique<Module>(ModuleIdentifier, Context);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005608 M->setMaterializer(R);
Rafael Espindolab7993462012-01-02 07:49:53 +00005609
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005610 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005611 if (Error Err =
5612 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
Peter Collingbourned9445c42016-11-13 07:00:17 +00005613 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005614
5615 if (MaterializeAll) {
5616 // Read in the entire module, and destroy the BitcodeReader.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00005617 if (Error Err = M->materializeAll())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005618 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005619 } else {
5620 // Resolve forward references from blockaddresses.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005621 if (Error Err = R->materializeForwardReferencedFunctions())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005622 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005623 }
5624 return std::move(M);
Chris Lattner6694f602007-04-29 07:54:31 +00005625}
5626
Peter Collingbourned9445c42016-11-13 07:00:17 +00005627Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005628BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5629 bool IsImporting) {
5630 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005631}
5632
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005633// Parse the specified bitcode buffer and merge the index into CombinedIndex.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005634// We don't use ModuleIdentifier here because the client may need to control the
5635// module path used in the combined summary (e.g. when reading summaries for
5636// regular LTO modules).
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005637Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005638 StringRef ModulePath, uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005639 BitstreamCursor Stream(Buffer);
5640 Stream.JumpToBit(ModuleBit);
5641
5642 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005643 ModulePath, ModuleId);
Peter Collingbourne440e2042017-05-01 22:48:10 +00005644 return R.parseModule();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005645}
5646
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005647// Parse the specified bitcode buffer, returning the function info index.
5648Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5649 BitstreamCursor Stream(Buffer);
5650 Stream.JumpToBit(ModuleBit);
5651
5652 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005653 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5654 ModuleIdentifier, 0);
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005655
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005656 if (Error Err = R.parseModule())
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005657 return std::move(Err);
5658
5659 return std::move(Index);
5660}
5661
5662// Check if the given bitcode buffer contains a global value summary block.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005663Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005664 BitstreamCursor Stream(Buffer);
5665 Stream.JumpToBit(ModuleBit);
5666
5667 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5668 return error("Invalid record");
5669
5670 while (true) {
5671 BitstreamEntry Entry = Stream.advance();
5672
5673 switch (Entry.Kind) {
5674 case BitstreamEntry::Error:
5675 return error("Malformed block");
5676 case BitstreamEntry::EndBlock:
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005677 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false};
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005678
5679 case BitstreamEntry::SubBlock:
5680 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005681 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true};
5682
5683 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID)
5684 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true};
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005685
5686 // Ignore other sub-blocks.
5687 if (Stream.SkipBlock())
5688 return error("Malformed block");
5689 continue;
5690
5691 case BitstreamEntry::Record:
5692 Stream.skipRecord(Entry.ID);
5693 continue;
5694 }
5695 }
5696}
5697
5698static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005699 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5700 if (!MsOrErr)
5701 return MsOrErr.takeError();
5702
5703 if (MsOrErr->size() != 1)
5704 return error("Expected a single module");
5705
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005706 return (*MsOrErr)[0];
5707}
5708
5709Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005710llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5711 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005712 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5713 if (!BM)
5714 return BM.takeError();
5715
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005716 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005717}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005718
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005719Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5720 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5721 bool ShouldLazyLoadMetadata, bool IsImporting) {
5722 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5723 IsImporting);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005724 if (MOrErr)
5725 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5726 return MOrErr;
5727}
5728
Peter Collingbourne7a748032016-11-16 21:44:45 +00005729Expected<std::unique_ptr<Module>>
5730BitcodeModule::parseModule(LLVMContext &Context) {
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005731 return getModuleImpl(Context, true, false, false);
Chad Rosierca2567b2011-12-07 21:44:12 +00005732 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5733 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00005734}
Bill Wendling0198ce02010-10-06 01:22:42 +00005735
Peter Collingbourne7a748032016-11-16 21:44:45 +00005736Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5737 LLVMContext &Context) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005738 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5739 if (!BM)
5740 return BM.takeError();
Peter Collingbourne7a748032016-11-16 21:44:45 +00005741
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005742 return BM->parseModule(Context);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005743}
5744
Peter Collingbournecd513a42016-11-11 19:50:24 +00005745Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5746 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005747 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005748 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005749
Peter Collingbournecd513a42016-11-11 19:50:24 +00005750 return readTriple(*StreamOrErr);
Bill Wendling0198ce02010-10-06 01:22:42 +00005751}
Teresa Johnson403a7872015-10-04 14:33:43 +00005752
Peter Collingbournecd513a42016-11-11 19:50:24 +00005753Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5754 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005755 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005756 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005757
Peter Collingbournecd513a42016-11-11 19:50:24 +00005758 return hasObjCCategory(*StreamOrErr);
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00005759}
5760
Peter Collingbournecd513a42016-11-11 19:50:24 +00005761Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5762 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005763 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005764 return StreamOrErr.takeError();
5765
5766 return readIdentificationCode(*StreamOrErr);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00005767}
5768
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005769Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
5770 ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005771 uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005772 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5773 if (!BM)
5774 return BM.takeError();
5775
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005776 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005777}
5778
Peter Collingbourne6de481a2016-11-11 19:50:39 +00005779Expected<std::unique_ptr<ModuleSummaryIndex>>
5780llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005781 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5782 if (!BM)
5783 return BM.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005784
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005785 return BM->getSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00005786}
5787
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005788Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005789 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5790 if (!BM)
5791 return BM.takeError();
Teresa Johnson403a7872015-10-04 14:33:43 +00005792
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005793 return BM->getLTOInfo();
Teresa Johnson403a7872015-10-04 14:33:43 +00005794}
Peter Collingbournec15d60b2017-05-01 20:42:32 +00005795
5796Expected<std::unique_ptr<ModuleSummaryIndex>>
Teresa Johnson4cd12ce2017-05-12 19:32:11 +00005797llvm::getModuleSummaryIndexForFile(StringRef Path,
5798 bool IgnoreEmptyThinLTOIndexFile) {
Peter Collingbournec15d60b2017-05-01 20:42:32 +00005799 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5800 MemoryBuffer::getFileOrSTDIN(Path);
5801 if (!FileOrErr)
5802 return errorCodeToError(FileOrErr.getError());
5803 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5804 return nullptr;
5805 return getModuleSummaryIndex(**FileOrErr);
5806}