blob: 12d5be55b8edd6048df160fffd459faa452ecc33 [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"
13
Eugene Zelenko1804a772016-08-25 00:45:04 +000014#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/None.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/SmallVector.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/ADT/StringRef.h"
David Majnemer3087b222015-01-20 05:58:07 +000023#include "llvm/ADT/Triple.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/ADT/Twine.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000025#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000026#include "llvm/Bitcode/LLVMBitCodes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000027#include "llvm/IR/Argument.h"
28#include "llvm/IR/Attributes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000029#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CallingConv.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000032#include "llvm/IR/CallSite.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Comdat.h"
34#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.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/DiagnosticInfo.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000041#include "llvm/IR/DiagnosticPrinter.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000042#include "llvm/IR/Function.h"
43#include "llvm/IR/GlobalAlias.h"
44#include "llvm/IR/GlobalIFunc.h"
45#include "llvm/IR/GlobalIndirectSymbol.h"
46#include "llvm/IR/GlobalObject.h"
47#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/GlobalVariable.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000049#include "llvm/IR/GVMaterializer.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/InlineAsm.h"
Mehdi Amini86623052016-12-16 19:16:29 +000051#include "llvm/IR/InstIterator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000052#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/Instructions.h"
55#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000056#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000058#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/OperandTraits.h"
60#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000061#include "llvm/IR/TrackingMDRef.h"
62#include "llvm/IR/Type.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000063#include "llvm/IR/ValueHandle.h"
Mehdi Amini86623052016-12-16 19:16:29 +000064#include "llvm/IR/Verifier.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000065#include "llvm/Support/AtomicOrdering.h"
66#include "llvm/Support/Casting.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000067#include "llvm/Support/CommandLine.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000068#include "llvm/Support/Compiler.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000069#include "llvm/Support/Debug.h"
Peter Collingbourne58f7f072016-11-09 00:51:04 +000070#include "llvm/Support/Error.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000071#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000072#include "llvm/Support/ManagedStatic.h"
Chris Lattner6694f602007-04-29 07:54:31 +000073#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000074#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000075#include <algorithm>
76#include <cassert>
77#include <cstddef>
78#include <cstdint>
Benjamin Kramercced8be2015-03-17 20:40:24 +000079#include <deque>
Eugene Zelenko1804a772016-08-25 00:45:04 +000080#include <limits>
81#include <map>
82#include <memory>
83#include <string>
84#include <system_error>
85#include <tuple>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000086#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000087#include <vector>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000088
Chris Lattner1314b992007-04-22 06:23:29 +000089using namespace llvm;
90
Teresa Johnson916495d2016-04-04 18:52:58 +000091static cl::opt<bool> PrintSummaryGUIDs(
92 "print-summary-global-ids", cl::init(false), cl::Hidden,
93 cl::desc(
94 "Print the global id for each value when reading the module summary"));
95
Peter Collingbournec15d60b2017-05-01 20:42:32 +000096// FIXME: This flag should either be removed or moved to clang as a driver flag.
97static llvm::cl::opt<bool> IgnoreEmptyThinLTOIndexFile(
98 "ignore-empty-index-file", llvm::cl::ZeroOrMore,
99 llvm::cl::desc(
100 "Ignore an empty index file and perform non-ThinLTO compilation"),
101 llvm::cl::init(false));
102
Benjamin Kramercced8be2015-03-17 20:40:24 +0000103namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000104
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +0000105enum {
106 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
107};
108
Peter Collingbournec0032b72016-11-11 19:50:10 +0000109Error error(const Twine &Message) {
110 return make_error<StringError>(
111 Message, make_error_code(BitcodeError::CorruptedBitcode));
112}
113
114/// Helper to read the header common to all bitcode files.
115bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
116 // Sniff for the signature.
117 if (!Stream.canSkipToPos(4) ||
118 Stream.Read(8) != 'B' ||
119 Stream.Read(8) != 'C' ||
120 Stream.Read(4) != 0x0 ||
121 Stream.Read(4) != 0xC ||
122 Stream.Read(4) != 0xE ||
123 Stream.Read(4) != 0xD)
124 return false;
125 return true;
126}
127
128Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
129 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
130 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
131
132 if (Buffer.getBufferSize() & 3)
133 return error("Invalid bitcode signature");
134
135 // If we have a wrapper header, parse it and ignore the non-bc file contents.
136 // The magic number is 0x0B17C0DE stored in little endian.
137 if (isBitcodeWrapper(BufPtr, BufEnd))
138 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
139 return error("Invalid bitcode wrapper header");
140
141 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
142 if (!hasValidBitcodeHeader(Stream))
143 return error("Invalid bitcode signature");
144
145 return std::move(Stream);
146}
147
Peter Collingbournecd513a42016-11-11 19:50:24 +0000148/// Convert a string from a record into an std::string, return true on failure.
149template <typename StrTy>
150static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
151 StrTy &Result) {
152 if (Idx > Record.size())
153 return true;
154
155 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
156 Result += (char)Record[i];
157 return false;
158}
159
Mehdi Amini86623052016-12-16 19:16:29 +0000160// Strip all the TBAA attachment for the module.
161void stripTBAA(Module *M) {
162 for (auto &F : *M) {
163 if (F.isMaterializable())
164 continue;
165 for (auto &I : instructions(F))
166 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
167 }
168}
169
Peter Collingbournecd513a42016-11-11 19:50:24 +0000170/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
171/// "epoch" encoded in the bitcode, and return the producer name if any.
172Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
173 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
174 return error("Invalid record");
175
176 // Read all the records.
177 SmallVector<uint64_t, 64> Record;
178
179 std::string ProducerIdentification;
180
181 while (true) {
182 BitstreamEntry Entry = Stream.advance();
183
184 switch (Entry.Kind) {
185 default:
186 case BitstreamEntry::Error:
187 return error("Malformed block");
188 case BitstreamEntry::EndBlock:
189 return ProducerIdentification;
190 case BitstreamEntry::Record:
191 // The interesting case.
192 break;
193 }
194
195 // Read a record.
196 Record.clear();
197 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
198 switch (BitCode) {
199 default: // Default behavior: reject
200 return error("Invalid value");
201 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
202 convertToString(Record, 0, ProducerIdentification);
203 break;
204 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
205 unsigned epoch = (unsigned)Record[0];
206 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
207 return error(
208 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
209 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
210 }
211 }
212 }
213 }
214}
215
216Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
217 // We expect a number of well-defined blocks, though we don't necessarily
218 // need to understand them all.
219 while (true) {
220 if (Stream.AtEndOfStream())
221 return "";
222
223 BitstreamEntry Entry = Stream.advance();
224 switch (Entry.Kind) {
225 case BitstreamEntry::EndBlock:
226 case BitstreamEntry::Error:
227 return error("Malformed block");
228
229 case BitstreamEntry::SubBlock:
230 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
231 return readIdentificationBlock(Stream);
232
233 // Ignore other sub-blocks.
234 if (Stream.SkipBlock())
235 return error("Malformed block");
236 continue;
237 case BitstreamEntry::Record:
238 Stream.skipRecord(Entry.ID);
239 continue;
240 }
241 }
242}
243
244Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
245 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
246 return error("Invalid record");
247
248 SmallVector<uint64_t, 64> Record;
249 // Read all the records for this module.
250
251 while (true) {
252 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
253
254 switch (Entry.Kind) {
255 case BitstreamEntry::SubBlock: // Handled for us already.
256 case BitstreamEntry::Error:
257 return error("Malformed block");
258 case BitstreamEntry::EndBlock:
259 return false;
260 case BitstreamEntry::Record:
261 // The interesting case.
262 break;
263 }
264
265 // Read a record.
266 switch (Stream.readRecord(Entry.ID, Record)) {
267 default:
268 break; // Default behavior, ignore unknown content.
269 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
270 std::string S;
271 if (convertToString(Record, 0, S))
272 return error("Invalid record");
273 // Check for the i386 and other (x86_64, ARM) conventions
274 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
275 S.find("__OBJC,__category") != std::string::npos)
276 return true;
277 break;
278 }
279 }
280 Record.clear();
281 }
282 llvm_unreachable("Exit infinite loop");
283}
284
285Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
286 // We expect a number of well-defined blocks, though we don't necessarily
287 // need to understand them all.
288 while (true) {
289 BitstreamEntry Entry = Stream.advance();
290
291 switch (Entry.Kind) {
292 case BitstreamEntry::Error:
293 return error("Malformed block");
294 case BitstreamEntry::EndBlock:
295 return false;
296
297 case BitstreamEntry::SubBlock:
298 if (Entry.ID == bitc::MODULE_BLOCK_ID)
299 return hasObjCCategoryInModule(Stream);
300
301 // Ignore other sub-blocks.
302 if (Stream.SkipBlock())
303 return error("Malformed block");
304 continue;
305
306 case BitstreamEntry::Record:
307 Stream.skipRecord(Entry.ID);
308 continue;
309 }
310 }
311}
312
313Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
314 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
315 return error("Invalid record");
316
317 SmallVector<uint64_t, 64> Record;
318
319 std::string Triple;
320
321 // Read all the records for this module.
322 while (true) {
323 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
324
325 switch (Entry.Kind) {
326 case BitstreamEntry::SubBlock: // Handled for us already.
327 case BitstreamEntry::Error:
328 return error("Malformed block");
329 case BitstreamEntry::EndBlock:
330 return Triple;
331 case BitstreamEntry::Record:
332 // The interesting case.
333 break;
334 }
335
336 // Read a record.
337 switch (Stream.readRecord(Entry.ID, Record)) {
338 default: break; // Default behavior, ignore unknown content.
339 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
340 std::string S;
341 if (convertToString(Record, 0, S))
342 return error("Invalid record");
343 Triple = S;
344 break;
345 }
346 }
347 Record.clear();
348 }
349 llvm_unreachable("Exit infinite loop");
350}
351
352Expected<std::string> readTriple(BitstreamCursor &Stream) {
353 // We expect a number of well-defined blocks, though we don't necessarily
354 // need to understand them all.
355 while (true) {
356 BitstreamEntry Entry = Stream.advance();
357
358 switch (Entry.Kind) {
359 case BitstreamEntry::Error:
360 return error("Malformed block");
361 case BitstreamEntry::EndBlock:
362 return "";
363
364 case BitstreamEntry::SubBlock:
365 if (Entry.ID == bitc::MODULE_BLOCK_ID)
366 return readModuleTriple(Stream);
367
368 // Ignore other sub-blocks.
369 if (Stream.SkipBlock())
370 return error("Malformed block");
371 continue;
372
373 case BitstreamEntry::Record:
374 Stream.skipRecord(Entry.ID);
375 continue;
376 }
377 }
378}
379
Peter Collingbourne6e860752016-09-23 18:27:42 +0000380class BitcodeReaderBase {
381protected:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000382 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
383 : Stream(std::move(Stream)), Strtab(Strtab) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000384 this->Stream.setBlockInfo(&BlockInfo);
385 }
Peter Collingbourne6e860752016-09-23 18:27:42 +0000386
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000387 BitstreamBlockInfo BlockInfo;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000388 BitstreamCursor Stream;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000389 StringRef Strtab;
390
391 /// In version 2 of the bitcode we store names of global values and comdats in
392 /// a string table rather than in the VST.
393 bool UseStrtab = false;
Peter Collingbourne6e860752016-09-23 18:27:42 +0000394
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000395 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
396
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000397 /// If this module uses a string table, pop the reference to the string table
398 /// and return the referenced string and the rest of the record. Otherwise
399 /// just return the record itself.
400 std::pair<StringRef, ArrayRef<uint64_t>>
401 readNameFromStrtab(ArrayRef<uint64_t> Record);
402
Peter Collingbourne939c7d92016-11-08 04:16:57 +0000403 bool readBlockInfo();
Peter Collingbourne6e860752016-09-23 18:27:42 +0000404
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000405 // Contains an arbitrary and optional string identifying the bitcode producer
406 std::string ProducerIdentification;
407
408 Error error(const Twine &Message);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000409};
410
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000411Error BitcodeReaderBase::error(const Twine &Message) {
412 std::string FullMsg = Message.str();
413 if (!ProducerIdentification.empty())
414 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
415 LLVM_VERSION_STRING "')";
Peter Collingbournec0032b72016-11-11 19:50:10 +0000416 return ::error(FullMsg);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000417}
418
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000419Expected<unsigned>
420BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
421 if (Record.size() < 1)
422 return error("Invalid record");
423 unsigned ModuleVersion = Record[0];
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000424 if (ModuleVersion > 2)
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000425 return error("Invalid value");
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000426 UseStrtab = ModuleVersion >= 2;
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000427 return ModuleVersion;
428}
429
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000430std::pair<StringRef, ArrayRef<uint64_t>>
431BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
432 if (!UseStrtab)
433 return {"", Record};
434 // Invalid reference. Let the caller complain about the record being empty.
435 if (Record[0] + Record[1] > Strtab.size())
436 return {"", {}};
437 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
438}
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
459 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000460 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000461 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
462 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000463 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.
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000482 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
483 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;
523
Benjamin Kramercced8be2015-03-17 20:40:24 +0000524public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000525 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
526 StringRef ProducerIdentification, LLVMContext &Context);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000527
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000528 Error materializeForwardReferencedFunctions();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000529
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000530 Error materialize(GlobalValue *GV) override;
531 Error materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000532 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000533
Rafael Espindola6ace6852015-06-15 21:02:49 +0000534 /// \brief Main interface to parsing a bitcode buffer.
535 /// \returns true if an error occurred.
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000536 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
537 bool IsImporting = false);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000538
Benjamin Kramercced8be2015-03-17 20:40:24 +0000539 static uint64_t decodeSignRotatedValue(uint64_t V);
540
541 /// Materialize any deferred Metadata block.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000542 Error materializeMetadata() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000543
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000544 void setStripDebugInfo() override;
545
Benjamin Kramercced8be2015-03-17 20:40:24 +0000546private:
547 std::vector<StructType *> IdentifiedStructTypes;
548 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
549 StructType *createIdentifiedStructType(LLVMContext &Context);
550
551 Type *getTypeByID(unsigned ID);
Eugene Zelenko1804a772016-08-25 00:45:04 +0000552
David Majnemer8a1c45d2015-12-12 05:38:55 +0000553 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000554 if (Ty && Ty->isMetadataTy())
555 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000556 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000557 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000558
Benjamin Kramercced8be2015-03-17 20:40:24 +0000559 Metadata *getFnMetadataByID(unsigned ID) {
Mehdi Amini3bb4d012017-01-20 20:29:16 +0000560 return MDLoader->getMetadataFwdRefOrLoad(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000561 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000562
Benjamin Kramercced8be2015-03-17 20:40:24 +0000563 BasicBlock *getBasicBlock(unsigned ID) const {
564 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
565 return FunctionBBs[ID];
566 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000567
Reid Klecknerb5180542017-03-21 16:57:19 +0000568 AttributeList getAttributes(unsigned i) const {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000569 if (i-1 < MAttributes.size())
570 return MAttributes[i-1];
Reid Klecknerb5180542017-03-21 16:57:19 +0000571 return AttributeList();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000572 }
573
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000574 /// Read a value/type pair out of the specified record from slot 'Slot'.
575 /// Increment Slot past the number of slots used in the record. Return true on
576 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000577 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
578 unsigned InstNum, Value *&ResVal) {
579 if (Slot == Record.size()) return true;
580 unsigned ValNo = (unsigned)Record[Slot++];
581 // Adjust the ValNo, if it was encoded relative to the InstNum.
582 if (UseRelativeIDs)
583 ValNo = InstNum - ValNo;
584 if (ValNo < InstNum) {
585 // If this is not a forward reference, just return the value we already
586 // have.
587 ResVal = getFnValueByID(ValNo, nullptr);
588 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000589 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000590 if (Slot == Record.size())
591 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000592
593 unsigned TypeNo = (unsigned)Record[Slot++];
594 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
595 return ResVal == nullptr;
596 }
597
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000598 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
599 /// past the number of slots used by the value in the record. Return true if
600 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000601 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000602 unsigned InstNum, Type *Ty, Value *&ResVal) {
603 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000604 return true;
605 // All values currently take a single record slot.
606 ++Slot;
607 return false;
608 }
609
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000610 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000611 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000612 unsigned InstNum, Type *Ty, Value *&ResVal) {
613 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000614 return ResVal == nullptr;
615 }
616
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000617 /// Version of getValue that returns ResVal directly, or 0 if there is an
618 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000619 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000620 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000621 if (Slot == Record.size()) return nullptr;
622 unsigned ValNo = (unsigned)Record[Slot];
623 // Adjust the ValNo, if it was encoded relative to the InstNum.
624 if (UseRelativeIDs)
625 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000626 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000627 }
628
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000629 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000630 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000631 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000632 if (Slot == Record.size()) return nullptr;
633 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
634 // Adjust the ValNo, if it was encoded relative to the InstNum.
635 if (UseRelativeIDs)
636 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000637 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000638 }
639
640 /// Converts alignment exponent (i.e. power of two (or zero)) to the
641 /// corresponding alignment to use. If alignment is too large, returns
642 /// a corresponding error code.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000643 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
644 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
645 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000646
647 Error parseComdatRecord(ArrayRef<uint64_t> Record);
648 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
649 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
650 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
651 ArrayRef<uint64_t> Record);
652
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000653 Error parseAttributeBlock();
654 Error parseAttributeGroupBlock();
655 Error parseTypeTable();
656 Error parseTypeTableBody();
657 Error parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000658
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000659 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
660 unsigned NameIndex, Triple &TT);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000661 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
662 ArrayRef<uint64_t> Record);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000663 Error parseValueSymbolTable(uint64_t Offset = 0);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000664 Error parseGlobalValueSymbolTable();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000665 Error parseConstants();
666 Error rememberAndSkipFunctionBodies();
667 Error rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000668 /// Save the positions of the Metadata blocks and skip parsing the blocks.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000669 Error rememberAndSkipMetadata();
670 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
671 Error parseFunctionBody(Function *F);
672 Error globalCleanup();
673 Error resolveGlobalAndIndirectSymbolInits();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000674 Error parseUseLists();
675 Error findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000676 Function *F,
677 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
678};
Teresa Johnson403a7872015-10-04 14:33:43 +0000679
680/// Class to manage reading and parsing function summary index bitcode
681/// files/sections.
Peter Collingbourne6e860752016-09-23 18:27:42 +0000682class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000683 /// The module index built during parsing.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +0000684 ModuleSummaryIndex &TheIndex;
Teresa Johnson403a7872015-10-04 14:33:43 +0000685
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000686 /// Indicates whether we have encountered a global value summary section
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000687 /// yet during parsing.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000688 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000689
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000690 /// Indicates whether we have already parsed the VST, used for error checking.
691 bool SeenValueSymbolTable = false;
692
693 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
694 /// Used to enable on-demand parsing of the VST.
695 uint64_t VSTOffset = 0;
696
697 // Map to save ValueId to GUID association that was recorded in the
698 // ValueSymbolTable. It is used after the VST is parsed to convert
699 // call graph edges read from the function summary from referencing
700 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000701 // they are recorded in the summary index being built.
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000702 // We save a second GUID which is the same as the first one, but ignoring the
703 // linkage, i.e. for value other than local linkage they are identical.
704 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
705 ValueIdToCallGraphGUIDMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000706
Teresa Johnson403a7872015-10-04 14:33:43 +0000707 /// Map populated during module path string table parsing, from the
708 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000709 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000710 /// summary records.
711 DenseMap<uint64_t, StringRef> ModuleIdMap;
712
Teresa Johnsone1164de2016-02-10 21:55:02 +0000713 /// Original source file name recorded in a bitcode record.
714 std::string SourceFileName;
715
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000716public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000717 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
718 ModuleSummaryIndex &TheIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +0000719
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000720 Error parseModule(StringRef ModulePath);
Teresa Johnson403a7872015-10-04 14:33:43 +0000721
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000722private:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000723 void setValueGUID(uint64_t ValueID, StringRef ValueName,
724 GlobalValue::LinkageTypes Linkage,
725 StringRef SourceFileName);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000726 Error parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000727 uint64_t Offset,
728 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000729 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
730 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
731 bool IsOldProfileFormat,
732 bool HasProfile);
Peter Collingbournec0032b72016-11-11 19:50:10 +0000733 Error parseEntireSummary(StringRef ModulePath);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000734 Error parseModuleStringTable();
Eugene Zelenko1804a772016-08-25 00:45:04 +0000735
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000736 std::pair<GlobalValue::GUID, GlobalValue::GUID>
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000737 getGUIDFromValueId(unsigned ValueId);
Teresa Johnson403a7872015-10-04 14:33:43 +0000738};
Eugene Zelenko1804a772016-08-25 00:45:04 +0000739
Peter Collingbournecd513a42016-11-11 19:50:24 +0000740} // end anonymous namespace
741
742std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
743 Error Err) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000744 if (Err) {
745 std::error_code EC;
746 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
747 EC = EIB.convertToErrorCode();
748 Ctx.emitError(EIB.message());
749 });
750 return EC;
751 }
752 return std::error_code();
753}
754
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000755BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne7a748032016-11-16 21:44:45 +0000756 StringRef ProducerIdentification,
757 LLVMContext &Context)
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000758 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
Mehdi Aminief27db82016-12-12 19:34:26 +0000759 ValueList(Context) {
Peter Collingbourne7a748032016-11-16 21:44:45 +0000760 this->ProducerIdentification = ProducerIdentification;
761}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000762
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000763Error BitcodeReader::materializeForwardReferencedFunctions() {
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000764 if (WillMaterializeAllForwardRefs)
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000765 return Error::success();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000766
767 // Prevent recursion.
768 WillMaterializeAllForwardRefs = true;
769
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000770 while (!BasicBlockFwdRefQueue.empty()) {
771 Function *F = BasicBlockFwdRefQueue.front();
772 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000773 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000774 if (!BasicBlockFwdRefs.count(F))
775 // Already materialized.
776 continue;
777
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000778 // Check for a function that isn't materializable to prevent an infinite
779 // loop. When parsing a blockaddress stored in a global variable, there
780 // isn't a trivial way to check if a function will have a body without a
781 // linear search through FunctionsWithBodies, so just check it here.
782 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000783 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000784
785 // Try to materialize F.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000786 if (Error Err = materialize(F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000787 return Err;
Rafael Espindolab7993462012-01-02 07:49:53 +0000788 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000789 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000790
791 // Reset state.
792 WillMaterializeAllForwardRefs = false;
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000793 return Error::success();
Rafael Espindolab7993462012-01-02 07:49:53 +0000794}
795
Chris Lattnerfee5a372007-05-04 03:30:17 +0000796//===----------------------------------------------------------------------===//
797// Helper functions to implement forward reference resolution, etc.
798//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000799
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000800static bool hasImplicitComdat(size_t Val) {
801 switch (Val) {
802 default:
803 return false;
804 case 1: // Old WeakAnyLinkage
805 case 4: // Old LinkOnceAnyLinkage
806 case 10: // Old WeakODRLinkage
807 case 11: // Old LinkOnceODRLinkage
808 return true;
809 }
810}
811
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000812static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000813 switch (Val) {
814 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000815 case 0:
816 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000817 case 2:
818 return GlobalValue::AppendingLinkage;
819 case 3:
820 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000821 case 5:
822 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
823 case 6:
824 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
825 case 7:
826 return GlobalValue::ExternalWeakLinkage;
827 case 8:
828 return GlobalValue::CommonLinkage;
829 case 9:
830 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000831 case 12:
832 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000833 case 13:
834 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
835 case 14:
836 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000837 case 15:
838 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000839 case 1: // Old value with implicit comdat.
840 case 16:
841 return GlobalValue::WeakAnyLinkage;
842 case 10: // Old value with implicit comdat.
843 case 17:
844 return GlobalValue::WeakODRLinkage;
845 case 4: // Old value with implicit comdat.
846 case 18:
847 return GlobalValue::LinkOnceAnyLinkage;
848 case 11: // Old value with implicit comdat.
849 case 19:
850 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000851 }
852}
853
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000854/// Decode the flags for GlobalValue in the summary.
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000855static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
856 uint64_t Version) {
857 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
858 // like getDecodedLinkage() above. Any future change to the linkage enum and
859 // to getDecodedLinkage() will need to be taken into account here as above.
860 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Amini1380edf2017-02-03 07:41:43 +0000861 RawFlags = RawFlags >> 4;
862 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000863 // The LiveRoot flag wasn't introduced until version 3. For dead stripping
864 // to work correctly on earlier versions, we must conservatively treat all
865 // values as live.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000866 bool LiveRoot = (RawFlags & 0x2) || Version < 3;
867 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, LiveRoot);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000868}
869
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000870static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000871 switch (Val) {
872 default: // Map unknown visibilities to default.
873 case 0: return GlobalValue::DefaultVisibility;
874 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000875 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000876 }
877}
878
Nico Rieck7157bb72014-01-14 15:22:47 +0000879static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000880getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000881 switch (Val) {
882 default: // Map unknown values to default.
883 case 0: return GlobalValue::DefaultStorageClass;
884 case 1: return GlobalValue::DLLImportStorageClass;
885 case 2: return GlobalValue::DLLExportStorageClass;
886 }
887}
888
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000889static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000890 switch (Val) {
891 case 0: return GlobalVariable::NotThreadLocal;
892 default: // Map unknown non-zero value to general dynamic.
893 case 1: return GlobalVariable::GeneralDynamicTLSModel;
894 case 2: return GlobalVariable::LocalDynamicTLSModel;
895 case 3: return GlobalVariable::InitialExecTLSModel;
896 case 4: return GlobalVariable::LocalExecTLSModel;
897 }
898}
899
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000900static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
901 switch (Val) {
902 default: // Map unknown to UnnamedAddr::None.
903 case 0: return GlobalVariable::UnnamedAddr::None;
904 case 1: return GlobalVariable::UnnamedAddr::Global;
905 case 2: return GlobalVariable::UnnamedAddr::Local;
906 }
907}
908
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000909static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000910 switch (Val) {
911 default: return -1;
912 case bitc::CAST_TRUNC : return Instruction::Trunc;
913 case bitc::CAST_ZEXT : return Instruction::ZExt;
914 case bitc::CAST_SEXT : return Instruction::SExt;
915 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
916 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
917 case bitc::CAST_UITOFP : return Instruction::UIToFP;
918 case bitc::CAST_SITOFP : return Instruction::SIToFP;
919 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
920 case bitc::CAST_FPEXT : return Instruction::FPExt;
921 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
922 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
923 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000924 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000925 }
926}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000927
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000928static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000929 bool IsFP = Ty->isFPOrFPVectorTy();
930 // BinOps are only valid for int/fp or vector of int/fp types
931 if (!IsFP && !Ty->isIntOrIntVectorTy())
932 return -1;
933
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000934 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000935 default:
936 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000937 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000938 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000939 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000940 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000941 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000942 return IsFP ? Instruction::FMul : Instruction::Mul;
943 case bitc::BINOP_UDIV:
944 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000945 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000946 return IsFP ? Instruction::FDiv : Instruction::SDiv;
947 case bitc::BINOP_UREM:
948 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000949 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000950 return IsFP ? Instruction::FRem : Instruction::SRem;
951 case bitc::BINOP_SHL:
952 return IsFP ? -1 : Instruction::Shl;
953 case bitc::BINOP_LSHR:
954 return IsFP ? -1 : Instruction::LShr;
955 case bitc::BINOP_ASHR:
956 return IsFP ? -1 : Instruction::AShr;
957 case bitc::BINOP_AND:
958 return IsFP ? -1 : Instruction::And;
959 case bitc::BINOP_OR:
960 return IsFP ? -1 : Instruction::Or;
961 case bitc::BINOP_XOR:
962 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000963 }
964}
965
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000966static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000967 switch (Val) {
968 default: return AtomicRMWInst::BAD_BINOP;
969 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
970 case bitc::RMW_ADD: return AtomicRMWInst::Add;
971 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
972 case bitc::RMW_AND: return AtomicRMWInst::And;
973 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
974 case bitc::RMW_OR: return AtomicRMWInst::Or;
975 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
976 case bitc::RMW_MAX: return AtomicRMWInst::Max;
977 case bitc::RMW_MIN: return AtomicRMWInst::Min;
978 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
979 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
980 }
981}
982
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000983static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000984 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +0000985 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
986 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
987 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
988 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
989 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
990 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000991 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +0000992 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000993 }
994}
995
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000996static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000997 switch (Val) {
998 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
999 default: // Map unknown scopes to cross-thread.
1000 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
1001 }
1002}
1003
David Majnemerdad0a642014-06-27 18:19:56 +00001004static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1005 switch (Val) {
1006 default: // Map unknown selection kinds to any.
1007 case bitc::COMDAT_SELECTION_KIND_ANY:
1008 return Comdat::Any;
1009 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1010 return Comdat::ExactMatch;
1011 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1012 return Comdat::Largest;
1013 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1014 return Comdat::NoDuplicates;
1015 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1016 return Comdat::SameSize;
1017 }
1018}
1019
James Molloy88eb5352015-07-10 12:52:00 +00001020static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1021 FastMathFlags FMF;
1022 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
1023 FMF.setUnsafeAlgebra();
1024 if (0 != (Val & FastMathFlags::NoNaNs))
1025 FMF.setNoNaNs();
1026 if (0 != (Val & FastMathFlags::NoInfs))
1027 FMF.setNoInfs();
1028 if (0 != (Val & FastMathFlags::NoSignedZeros))
1029 FMF.setNoSignedZeros();
1030 if (0 != (Val & FastMathFlags::AllowReciprocal))
1031 FMF.setAllowReciprocal();
Adam Nemetcd847a82017-03-28 20:11:52 +00001032 if (0 != (Val & FastMathFlags::AllowContract))
1033 FMF.setAllowContract(true);
James Molloy88eb5352015-07-10 12:52:00 +00001034 return FMF;
1035}
1036
Eugene Zelenko1804a772016-08-25 00:45:04 +00001037static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001038 switch (Val) {
1039 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1040 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1041 }
1042}
1043
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001044
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001045Type *BitcodeReader::getTypeByID(unsigned ID) {
1046 // The type table size is always specified correctly.
1047 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001048 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001049
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001050 if (Type *Ty = TypeList[ID])
1051 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001052
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001053 // If we have a forward reference, the only possible case is when it is to a
1054 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001055 return TypeList[ID] = createIdentifiedStructType(Context);
1056}
1057
1058StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1059 StringRef Name) {
1060 auto *Ret = StructType::create(Context, Name);
1061 IdentifiedStructTypes.push_back(Ret);
1062 return Ret;
1063}
1064
1065StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1066 auto *Ret = StructType::create(Context);
1067 IdentifiedStructTypes.push_back(Ret);
1068 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001069}
1070
Chris Lattnerfee5a372007-05-04 03:30:17 +00001071//===----------------------------------------------------------------------===//
1072// Functions for parsing blocks from the bitcode file
1073//===----------------------------------------------------------------------===//
1074
Amaury Sechet74084c42016-11-06 07:48:46 +00001075static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1076 switch (Val) {
1077 case Attribute::EndAttrKinds:
1078 llvm_unreachable("Synthetic enumerators which should never get here");
1079
1080 case Attribute::None: return 0;
1081 case Attribute::ZExt: return 1 << 0;
1082 case Attribute::SExt: return 1 << 1;
1083 case Attribute::NoReturn: return 1 << 2;
1084 case Attribute::InReg: return 1 << 3;
1085 case Attribute::StructRet: return 1 << 4;
1086 case Attribute::NoUnwind: return 1 << 5;
1087 case Attribute::NoAlias: return 1 << 6;
1088 case Attribute::ByVal: return 1 << 7;
1089 case Attribute::Nest: return 1 << 8;
1090 case Attribute::ReadNone: return 1 << 9;
1091 case Attribute::ReadOnly: return 1 << 10;
1092 case Attribute::NoInline: return 1 << 11;
1093 case Attribute::AlwaysInline: return 1 << 12;
1094 case Attribute::OptimizeForSize: return 1 << 13;
1095 case Attribute::StackProtect: return 1 << 14;
1096 case Attribute::StackProtectReq: return 1 << 15;
1097 case Attribute::Alignment: return 31 << 16;
1098 case Attribute::NoCapture: return 1 << 21;
1099 case Attribute::NoRedZone: return 1 << 22;
1100 case Attribute::NoImplicitFloat: return 1 << 23;
1101 case Attribute::Naked: return 1 << 24;
1102 case Attribute::InlineHint: return 1 << 25;
1103 case Attribute::StackAlignment: return 7 << 26;
1104 case Attribute::ReturnsTwice: return 1 << 29;
1105 case Attribute::UWTable: return 1 << 30;
1106 case Attribute::NonLazyBind: return 1U << 31;
1107 case Attribute::SanitizeAddress: return 1ULL << 32;
1108 case Attribute::MinSize: return 1ULL << 33;
1109 case Attribute::NoDuplicate: return 1ULL << 34;
1110 case Attribute::StackProtectStrong: return 1ULL << 35;
1111 case Attribute::SanitizeThread: return 1ULL << 36;
1112 case Attribute::SanitizeMemory: return 1ULL << 37;
1113 case Attribute::NoBuiltin: return 1ULL << 38;
1114 case Attribute::Returned: return 1ULL << 39;
1115 case Attribute::Cold: return 1ULL << 40;
1116 case Attribute::Builtin: return 1ULL << 41;
1117 case Attribute::OptimizeNone: return 1ULL << 42;
1118 case Attribute::InAlloca: return 1ULL << 43;
1119 case Attribute::NonNull: return 1ULL << 44;
1120 case Attribute::JumpTable: return 1ULL << 45;
1121 case Attribute::Convergent: return 1ULL << 46;
1122 case Attribute::SafeStack: return 1ULL << 47;
1123 case Attribute::NoRecurse: return 1ULL << 48;
1124 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1125 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1126 case Attribute::SwiftSelf: return 1ULL << 51;
1127 case Attribute::SwiftError: return 1ULL << 52;
1128 case Attribute::WriteOnly: return 1ULL << 53;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001129 case Attribute::Speculatable: return 1ULL << 54;
Amaury Sechet74084c42016-11-06 07:48:46 +00001130 case Attribute::Dereferenceable:
1131 llvm_unreachable("dereferenceable attribute not supported in raw format");
1132 break;
1133 case Attribute::DereferenceableOrNull:
1134 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1135 "format");
1136 break;
1137 case Attribute::ArgMemOnly:
1138 llvm_unreachable("argmemonly attribute not supported in raw format");
1139 break;
1140 case Attribute::AllocSize:
1141 llvm_unreachable("allocsize not supported in raw format");
1142 break;
1143 }
1144 llvm_unreachable("Unsupported attribute type");
1145}
1146
1147static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1148 if (!Val) return;
1149
1150 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1151 I = Attribute::AttrKind(I + 1)) {
1152 if (I == Attribute::Dereferenceable ||
1153 I == Attribute::DereferenceableOrNull ||
1154 I == Attribute::ArgMemOnly ||
1155 I == Attribute::AllocSize)
1156 continue;
1157 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1158 if (I == Attribute::Alignment)
1159 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1160 else if (I == Attribute::StackAlignment)
1161 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1162 else
1163 B.addAttribute(I);
1164 }
1165 }
1166}
1167
Bill Wendling56aeccc2013-02-04 23:32:23 +00001168/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1169/// been decoded from the given integer. This function must stay in sync with
1170/// 'encodeLLVMAttributesForBitcode'.
1171static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1172 uint64_t EncodedAttrs) {
1173 // FIXME: Remove in 4.0.
1174
1175 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1176 // the bits above 31 down by 11 bits.
1177 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1178 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1179 "Alignment must be a power of two.");
1180
1181 if (Alignment)
1182 B.addAlignmentAttr(Alignment);
Amaury Sechet74084c42016-11-06 07:48:46 +00001183 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1184 (EncodedAttrs & 0xffff));
Bill Wendling56aeccc2013-02-04 23:32:23 +00001185}
1186
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001187Error BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001188 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001189 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001190
Devang Patela05633e2008-09-26 22:53:05 +00001191 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001192 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001193
Chris Lattnerfee5a372007-05-04 03:30:17 +00001194 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001195
Reid Klecknerb5180542017-03-21 16:57:19 +00001196 SmallVector<AttributeList, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001197
Chris Lattnerfee5a372007-05-04 03:30:17 +00001198 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001199 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001200 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001201
Chris Lattner27d38752013-01-20 02:13:19 +00001202 switch (Entry.Kind) {
1203 case BitstreamEntry::SubBlock: // Handled for us already.
1204 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001205 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001206 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001207 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001208 case BitstreamEntry::Record:
1209 // The interesting case.
1210 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001211 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001212
Chris Lattnerfee5a372007-05-04 03:30:17 +00001213 // Read a record.
1214 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001215 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001216 default: // Default behavior: ignore.
1217 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001218 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1219 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001220 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001221 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001222
Chris Lattnerfee5a372007-05-04 03:30:17 +00001223 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001224 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001225 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Reid Klecknerb5180542017-03-21 16:57:19 +00001226 Attrs.push_back(AttributeList::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001227 }
Devang Patela05633e2008-09-26 22:53:05 +00001228
Reid Klecknerb5180542017-03-21 16:57:19 +00001229 MAttributes.push_back(AttributeList::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001230 Attrs.clear();
1231 break;
1232 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001233 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1234 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1235 Attrs.push_back(MAttributeGroups[Record[i]]);
1236
Reid Klecknerb5180542017-03-21 16:57:19 +00001237 MAttributes.push_back(AttributeList::get(Context, Attrs));
Bill Wendling0dc08912013-02-12 08:13:50 +00001238 Attrs.clear();
1239 break;
1240 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001241 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001242 }
1243}
1244
Reid Klecknere9f36af2013-11-12 01:31:00 +00001245// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001246static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001247 switch (Code) {
1248 default:
1249 return Attribute::None;
1250 case bitc::ATTR_KIND_ALIGNMENT:
1251 return Attribute::Alignment;
1252 case bitc::ATTR_KIND_ALWAYS_INLINE:
1253 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001254 case bitc::ATTR_KIND_ARGMEMONLY:
1255 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001256 case bitc::ATTR_KIND_BUILTIN:
1257 return Attribute::Builtin;
1258 case bitc::ATTR_KIND_BY_VAL:
1259 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001260 case bitc::ATTR_KIND_IN_ALLOCA:
1261 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001262 case bitc::ATTR_KIND_COLD:
1263 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001264 case bitc::ATTR_KIND_CONVERGENT:
1265 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001266 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1267 return Attribute::InaccessibleMemOnly;
1268 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1269 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001270 case bitc::ATTR_KIND_INLINE_HINT:
1271 return Attribute::InlineHint;
1272 case bitc::ATTR_KIND_IN_REG:
1273 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001274 case bitc::ATTR_KIND_JUMP_TABLE:
1275 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001276 case bitc::ATTR_KIND_MIN_SIZE:
1277 return Attribute::MinSize;
1278 case bitc::ATTR_KIND_NAKED:
1279 return Attribute::Naked;
1280 case bitc::ATTR_KIND_NEST:
1281 return Attribute::Nest;
1282 case bitc::ATTR_KIND_NO_ALIAS:
1283 return Attribute::NoAlias;
1284 case bitc::ATTR_KIND_NO_BUILTIN:
1285 return Attribute::NoBuiltin;
1286 case bitc::ATTR_KIND_NO_CAPTURE:
1287 return Attribute::NoCapture;
1288 case bitc::ATTR_KIND_NO_DUPLICATE:
1289 return Attribute::NoDuplicate;
1290 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1291 return Attribute::NoImplicitFloat;
1292 case bitc::ATTR_KIND_NO_INLINE:
1293 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001294 case bitc::ATTR_KIND_NO_RECURSE:
1295 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001296 case bitc::ATTR_KIND_NON_LAZY_BIND:
1297 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001298 case bitc::ATTR_KIND_NON_NULL:
1299 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001300 case bitc::ATTR_KIND_DEREFERENCEABLE:
1301 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001302 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1303 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001304 case bitc::ATTR_KIND_ALLOC_SIZE:
1305 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001306 case bitc::ATTR_KIND_NO_RED_ZONE:
1307 return Attribute::NoRedZone;
1308 case bitc::ATTR_KIND_NO_RETURN:
1309 return Attribute::NoReturn;
1310 case bitc::ATTR_KIND_NO_UNWIND:
1311 return Attribute::NoUnwind;
1312 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1313 return Attribute::OptimizeForSize;
1314 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1315 return Attribute::OptimizeNone;
1316 case bitc::ATTR_KIND_READ_NONE:
1317 return Attribute::ReadNone;
1318 case bitc::ATTR_KIND_READ_ONLY:
1319 return Attribute::ReadOnly;
1320 case bitc::ATTR_KIND_RETURNED:
1321 return Attribute::Returned;
1322 case bitc::ATTR_KIND_RETURNS_TWICE:
1323 return Attribute::ReturnsTwice;
1324 case bitc::ATTR_KIND_S_EXT:
1325 return Attribute::SExt;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001326 case bitc::ATTR_KIND_SPECULATABLE:
1327 return Attribute::Speculatable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001328 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1329 return Attribute::StackAlignment;
1330 case bitc::ATTR_KIND_STACK_PROTECT:
1331 return Attribute::StackProtect;
1332 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1333 return Attribute::StackProtectReq;
1334 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1335 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001336 case bitc::ATTR_KIND_SAFESTACK:
1337 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001338 case bitc::ATTR_KIND_STRUCT_RET:
1339 return Attribute::StructRet;
1340 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1341 return Attribute::SanitizeAddress;
1342 case bitc::ATTR_KIND_SANITIZE_THREAD:
1343 return Attribute::SanitizeThread;
1344 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1345 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001346 case bitc::ATTR_KIND_SWIFT_ERROR:
1347 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001348 case bitc::ATTR_KIND_SWIFT_SELF:
1349 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001350 case bitc::ATTR_KIND_UW_TABLE:
1351 return Attribute::UWTable;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001352 case bitc::ATTR_KIND_WRITEONLY:
1353 return Attribute::WriteOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001354 case bitc::ATTR_KIND_Z_EXT:
1355 return Attribute::ZExt;
1356 }
1357}
1358
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001359Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1360 unsigned &Alignment) {
JF Bastien30bf96b2015-02-22 19:32:03 +00001361 // Note: Alignment in bitcode files is incremented by 1, so that zero
1362 // can be used for default alignment.
1363 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001364 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001365 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001366 return Error::success();
JF Bastien30bf96b2015-02-22 19:32:03 +00001367}
1368
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001369Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001370 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001371 if (*Kind == Attribute::None)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001372 return error("Unknown attribute kind (" + Twine(Code) + ")");
1373 return Error::success();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001374}
1375
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001376Error BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001377 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001378 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001379
1380 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001381 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001382
1383 SmallVector<uint64_t, 64> Record;
1384
1385 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001386 while (true) {
Bill Wendlingba629332013-02-10 23:24:25 +00001387 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1388
1389 switch (Entry.Kind) {
1390 case BitstreamEntry::SubBlock: // Handled for us already.
1391 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001392 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001393 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001394 return Error::success();
Bill Wendlingba629332013-02-10 23:24:25 +00001395 case BitstreamEntry::Record:
1396 // The interesting case.
1397 break;
1398 }
1399
1400 // Read a record.
1401 Record.clear();
1402 switch (Stream.readRecord(Entry.ID, Record)) {
1403 default: // Default behavior: ignore.
1404 break;
1405 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1406 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001407 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001408
Bill Wendlinge46707e2013-02-11 22:32:29 +00001409 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001410 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1411
1412 AttrBuilder B;
1413 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1414 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001415 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001416 if (Error Err = parseAttrKind(Record[++i], &Kind))
1417 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001418
1419 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001420 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001421 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001422 if (Error Err = parseAttrKind(Record[++i], &Kind))
1423 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001424 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001425 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001426 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001427 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001428 else if (Kind == Attribute::Dereferenceable)
1429 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001430 else if (Kind == Attribute::DereferenceableOrNull)
1431 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001432 else if (Kind == Attribute::AllocSize)
1433 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001434 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001435 assert((Record[i] == 3 || Record[i] == 4) &&
1436 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001437 bool HasValue = (Record[i++] == 4);
1438 SmallString<64> KindStr;
1439 SmallString<64> ValStr;
1440
1441 while (Record[i] != 0 && i != e)
1442 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001443 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001444
1445 if (HasValue) {
1446 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001447 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001448 while (Record[i] != 0 && i != e)
1449 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001450 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001451 }
1452
1453 B.addAttribute(KindStr.str(), ValStr.str());
1454 }
1455 }
1456
Reid Klecknerb5180542017-03-21 16:57:19 +00001457 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001458 break;
1459 }
1460 }
1461 }
1462}
1463
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001464Error BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001465 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001466 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001467
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001468 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001469}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001470
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001471Error BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001472 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001473 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001474
1475 SmallVector<uint64_t, 64> Record;
1476 unsigned NumRecords = 0;
1477
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001478 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001479
Chris Lattner1314b992007-04-22 06:23:29 +00001480 // Read all the records for this type table.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001481 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001482 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001483
Chris Lattner27d38752013-01-20 02:13:19 +00001484 switch (Entry.Kind) {
1485 case BitstreamEntry::SubBlock: // Handled for us already.
1486 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001487 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001488 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001489 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001490 return error("Malformed block");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001491 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001492 case BitstreamEntry::Record:
1493 // The interesting case.
1494 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001495 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001496
Chris Lattner1314b992007-04-22 06:23:29 +00001497 // Read a record.
1498 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001499 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001500 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001501 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001502 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001503 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1504 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1505 // type list. This allows us to reserve space.
1506 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001507 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001508 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001509 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001510 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001511 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001512 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001513 case bitc::TYPE_CODE_HALF: // HALF
1514 ResultTy = Type::getHalfTy(Context);
1515 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001516 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001517 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001518 break;
1519 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001520 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001521 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001522 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001523 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001524 break;
1525 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001526 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001527 break;
1528 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001529 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001530 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001531 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001532 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001533 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001534 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001535 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001536 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001537 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1538 ResultTy = Type::getX86_MMXTy(Context);
1539 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001540 case bitc::TYPE_CODE_TOKEN: // TOKEN
1541 ResultTy = Type::getTokenTy(Context);
1542 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001543 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001544 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001545 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001546
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001547 uint64_t NumBits = Record[0];
1548 if (NumBits < IntegerType::MIN_INT_BITS ||
1549 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001550 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001551 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001552 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001553 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001554 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001555 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001556 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001557 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001558 unsigned AddressSpace = 0;
1559 if (Record.size() == 2)
1560 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001561 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001562 if (!ResultTy ||
1563 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001564 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001565 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001566 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001567 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001568 case bitc::TYPE_CODE_FUNCTION_OLD: {
1569 // FIXME: attrid is dead, remove it in LLVM 4.0
1570 // FUNCTION: [vararg, attrid, retty, paramty x N]
1571 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001572 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001573 SmallVector<Type*, 8> ArgTys;
1574 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1575 if (Type *T = getTypeByID(Record[i]))
1576 ArgTys.push_back(T);
1577 else
1578 break;
1579 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001580
Nuno Lopes561dae02012-05-23 15:19:39 +00001581 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001582 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001583 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001584
1585 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1586 break;
1587 }
Chad Rosier95898722011-11-03 00:14:01 +00001588 case bitc::TYPE_CODE_FUNCTION: {
1589 // FUNCTION: [vararg, retty, paramty x N]
1590 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001591 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001592 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001593 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001594 if (Type *T = getTypeByID(Record[i])) {
1595 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001596 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001597 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001598 }
Chad Rosier95898722011-11-03 00:14:01 +00001599 else
1600 break;
1601 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001602
Chad Rosier95898722011-11-03 00:14:01 +00001603 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001604 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001605 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001606
1607 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1608 break;
1609 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001610 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001611 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001612 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001613 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001614 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1615 if (Type *T = getTypeByID(Record[i]))
1616 EltTys.push_back(T);
1617 else
1618 break;
1619 }
1620 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001621 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001622 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001623 break;
1624 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001625 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001626 if (convertToString(Record, 0, TypeName))
1627 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001628 continue;
1629
1630 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1631 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001632 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001633
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001634 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001635 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001636
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001637 // Check to see if this was forward referenced, if so fill in the temp.
1638 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1639 if (Res) {
1640 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001641 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001642 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001643 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001644 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001645
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001646 SmallVector<Type*, 8> EltTys;
1647 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1648 if (Type *T = getTypeByID(Record[i]))
1649 EltTys.push_back(T);
1650 else
1651 break;
1652 }
1653 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001654 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001655 Res->setBody(EltTys, Record[0]);
1656 ResultTy = Res;
1657 break;
1658 }
1659 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1660 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001661 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001662
1663 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001664 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001665
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001666 // Check to see if this was forward referenced, if so fill in the temp.
1667 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1668 if (Res) {
1669 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001670 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001671 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001672 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001673 TypeName.clear();
1674 ResultTy = Res;
1675 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001676 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001677 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1678 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001679 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001680 ResultTy = getTypeByID(Record[1]);
1681 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001682 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001683 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001684 break;
1685 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1686 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001687 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001688 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001689 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001690 ResultTy = getTypeByID(Record[1]);
1691 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001692 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001693 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001694 break;
1695 }
1696
1697 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001698 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001699 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001700 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001701 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001702 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001703 TypeList[NumRecords++] = ResultTy;
1704 }
1705}
1706
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001707Error BitcodeReader::parseOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001708 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1709 return error("Invalid record");
1710
1711 if (!BundleTags.empty())
1712 return error("Invalid multiple blocks");
1713
1714 SmallVector<uint64_t, 64> Record;
1715
Eugene Zelenko1804a772016-08-25 00:45:04 +00001716 while (true) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001717 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1718
1719 switch (Entry.Kind) {
1720 case BitstreamEntry::SubBlock: // Handled for us already.
1721 case BitstreamEntry::Error:
1722 return error("Malformed block");
1723 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001724 return Error::success();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001725 case BitstreamEntry::Record:
1726 // The interesting case.
1727 break;
1728 }
1729
1730 // Tags are implicitly mapped to integers by their order.
1731
1732 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1733 return error("Invalid record");
1734
1735 // OPERAND_BUNDLE_TAG: [strchr x N]
1736 BundleTags.emplace_back();
1737 if (convertToString(Record, 0, BundleTags.back()))
1738 return error("Invalid record");
1739 Record.clear();
1740 }
1741}
1742
Teresa Johnsonff642b92015-09-17 20:12:00 +00001743/// Associate a value with its name from the given index in the provided record.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001744Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1745 unsigned NameIndex, Triple &TT) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001746 SmallString<128> ValueName;
1747 if (convertToString(Record, NameIndex, ValueName))
1748 return error("Invalid record");
1749 unsigned ValueID = Record[0];
1750 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1751 return error("Invalid record");
1752 Value *V = ValueList[ValueID];
1753
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001754 StringRef NameStr(ValueName.data(), ValueName.size());
1755 if (NameStr.find_first_of(0) != StringRef::npos)
1756 return error("Invalid value name");
1757 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001758 auto *GO = dyn_cast<GlobalObject>(V);
1759 if (GO) {
1760 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1761 if (TT.isOSBinFormatMachO())
1762 GO->setComdat(nullptr);
1763 else
1764 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1765 }
1766 }
1767 return V;
1768}
1769
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001770/// Helper to note and return the current location, and jump to the given
1771/// offset.
1772static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1773 BitstreamCursor &Stream) {
1774 // Save the current parsing location so we can jump back at the end
1775 // of the VST read.
1776 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1777 Stream.JumpToBit(Offset * 32);
1778#ifndef NDEBUG
1779 // Do some checking if we are in debug mode.
1780 BitstreamEntry Entry = Stream.advance();
1781 assert(Entry.Kind == BitstreamEntry::SubBlock);
1782 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1783#else
1784 // In NDEBUG mode ignore the output so we don't get an unused variable
1785 // warning.
1786 Stream.advance();
1787#endif
1788 return CurrentBit;
1789}
1790
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001791void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1792 Function *F,
1793 ArrayRef<uint64_t> Record) {
1794 // Note that we subtract 1 here because the offset is relative to one word
1795 // before the start of the identification or module block, which was
1796 // historically always the start of the regular bitcode header.
1797 uint64_t FuncWordOffset = Record[1] - 1;
1798 uint64_t FuncBitOffset = FuncWordOffset * 32;
1799 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1800 // Set the LastFunctionBlockBit to point to the last function block.
1801 // Later when parsing is resumed after function materialization,
1802 // we can simply skip that last function block.
1803 if (FuncBitOffset > LastFunctionBlockBit)
1804 LastFunctionBlockBit = FuncBitOffset;
1805}
1806
1807/// Read a new-style GlobalValue symbol table.
1808Error BitcodeReader::parseGlobalValueSymbolTable() {
1809 unsigned FuncBitcodeOffsetDelta =
1810 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1811
1812 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1813 return error("Invalid record");
1814
1815 SmallVector<uint64_t, 64> Record;
1816 while (true) {
1817 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1818
1819 switch (Entry.Kind) {
1820 case BitstreamEntry::SubBlock:
1821 case BitstreamEntry::Error:
1822 return error("Malformed block");
1823 case BitstreamEntry::EndBlock:
1824 return Error::success();
1825 case BitstreamEntry::Record:
1826 break;
1827 }
1828
1829 Record.clear();
1830 switch (Stream.readRecord(Entry.ID, Record)) {
1831 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1832 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1833 cast<Function>(ValueList[Record[0]]), Record);
1834 break;
1835 }
1836 }
1837}
1838
Teresa Johnsonff642b92015-09-17 20:12:00 +00001839/// Parse the value symbol table at either the current parsing location or
1840/// at the given bit offset if provided.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001841Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001842 uint64_t CurrentBit;
1843 // Pass in the Offset to distinguish between calling for the module-level
1844 // VST (where we want to jump to the VST offset) and the function-level
1845 // VST (where we don't).
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001846 if (Offset > 0) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001847 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001848 // If this module uses a string table, read this as a module-level VST.
1849 if (UseStrtab) {
1850 if (Error Err = parseGlobalValueSymbolTable())
1851 return Err;
1852 Stream.JumpToBit(CurrentBit);
1853 return Error::success();
1854 }
1855 // Otherwise, the VST will be in a similar format to a function-level VST,
1856 // and will contain symbol names.
1857 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001858
1859 // Compute the delta between the bitcode indices in the VST (the word offset
1860 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1861 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1862 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1863 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1864 // just before entering the VST subblock because: 1) the EnterSubBlock
1865 // changes the AbbrevID width; 2) the VST block is nested within the same
1866 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1867 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1868 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1869 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1870 unsigned FuncBitcodeOffsetDelta =
1871 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1872
Chris Lattner982ec1e2007-05-05 00:17:00 +00001873 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001874 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001875
1876 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001877
David Majnemer3087b222015-01-20 05:58:07 +00001878 Triple TT(TheModule->getTargetTriple());
1879
Chris Lattnerccaa4482007-04-23 21:26:05 +00001880 // Read all the records for this value table.
1881 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00001882
1883 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001884 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001885
Chris Lattner27d38752013-01-20 02:13:19 +00001886 switch (Entry.Kind) {
1887 case BitstreamEntry::SubBlock: // Handled for us already.
1888 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001889 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001890 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001891 if (Offset > 0)
1892 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001893 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001894 case BitstreamEntry::Record:
1895 // The interesting case.
1896 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001897 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001898
Chris Lattnerccaa4482007-04-23 21:26:05 +00001899 // Read a record.
1900 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001901 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001902 default: // Default behavior: unknown type.
1903 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001904 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001905 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1906 if (Error Err = ValOrErr.takeError())
1907 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001908 ValOrErr.get();
1909 break;
1910 }
1911 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001912 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001913 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1914 if (Error Err = ValOrErr.takeError())
1915 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001916 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001917
Peter Collingbournedb4cafa2017-04-06 19:39:24 +00001918 // Ignore function offsets emitted for aliases of functions in older
1919 // versions of LLVM.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001920 if (auto *F = dyn_cast<Function>(V))
1921 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001922 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001923 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001924 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001925 if (convertToString(Record, 1, ValueName))
1926 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001927 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001928 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001929 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001930
Daniel Dunbard786b512009-07-26 00:34:27 +00001931 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001932 ValueName.clear();
1933 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001934 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001935 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001936 }
1937}
1938
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001939/// Decode a signed value stored with the sign bit in the LSB for dense VBR
1940/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001941uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001942 if ((V & 1) == 0)
1943 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001945 return -(V >> 1);
1946 // There is no such thing as -0 with integers. "-0" really means MININT.
1947 return 1ULL << 63;
1948}
1949
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001950/// Resolve all of the initializers for global values and aliases that we can.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001951Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00001952 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001953 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
1954 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001955 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001956 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00001957 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
Chris Lattner44c17072007-04-26 02:46:40 +00001959 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001960 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001961 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001962 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00001963 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00001964
1965 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00001966 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001967 if (ValID >= ValueList.size()) {
1968 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00001969 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001970 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001971 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00001972 GlobalInitWorklist.back().first->setInitializer(C);
1973 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001974 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00001975 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001976 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001977 }
1978
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001979 while (!IndirectSymbolInitWorklist.empty()) {
1980 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001981 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001982 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001983 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00001984 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
1985 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001986 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001987 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
1988 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001989 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001990 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00001991 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001992 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001993 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001994
1995 while (!FunctionPrefixWorklist.empty()) {
1996 unsigned ValID = FunctionPrefixWorklist.back().second;
1997 if (ValID >= ValueList.size()) {
1998 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1999 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002000 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002001 FunctionPrefixWorklist.back().first->setPrefixData(C);
2002 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002003 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002004 }
2005 FunctionPrefixWorklist.pop_back();
2006 }
2007
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002008 while (!FunctionPrologueWorklist.empty()) {
2009 unsigned ValID = FunctionPrologueWorklist.back().second;
2010 if (ValID >= ValueList.size()) {
2011 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2012 } else {
2013 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2014 FunctionPrologueWorklist.back().first->setPrologueData(C);
2015 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002016 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002017 }
2018 FunctionPrologueWorklist.pop_back();
2019 }
2020
David Majnemer7fddecc2015-06-17 20:52:32 +00002021 while (!FunctionPersonalityFnWorklist.empty()) {
2022 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2023 if (ValID >= ValueList.size()) {
2024 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2025 } else {
2026 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2027 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2028 else
2029 return error("Expected a constant");
2030 }
2031 FunctionPersonalityFnWorklist.pop_back();
2032 }
2033
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002034 return Error::success();
Chris Lattner44c17072007-04-26 02:46:40 +00002035}
2036
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002037static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002038 SmallVector<uint64_t, 8> Words(Vals.size());
David Majnemer2d006e72016-08-12 04:32:42 +00002039 transform(Vals, Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002040 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002041
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002042 return APInt(TypeBits, Words);
2043}
2044
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002045Error BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002046 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002047 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002048
2049 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002050
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002051 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002052 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002053 unsigned NextCstNo = ValueList.size();
Eugene Zelenko1804a772016-08-25 00:45:04 +00002054
2055 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002056 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002057
Chris Lattner27d38752013-01-20 02:13:19 +00002058 switch (Entry.Kind) {
2059 case BitstreamEntry::SubBlock: // Handled for us already.
2060 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002061 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002062 case BitstreamEntry::EndBlock:
2063 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002064 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002065
Chris Lattner27d38752013-01-20 02:13:19 +00002066 // Once all the constants have been read, go through and resolve forward
2067 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002068 ValueList.resolveConstantForwardRefs();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002069 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002070 case BitstreamEntry::Record:
2071 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002072 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002073 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002074
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002075 // Read a record.
2076 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002077 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002078 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002079 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002080 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002081 default: // Default behavior: unknown constant
2082 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002083 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002084 break;
2085 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2086 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002087 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002088 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002089 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002090 if (TypeList[Record[0]] == VoidType)
2091 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002092 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002093 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002094 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002095 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002096 break;
2097 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002098 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002099 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002100 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002101 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002102 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002103 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002104 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002105
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002106 APInt VInt =
2107 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002108 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002109
Chris Lattner08feb1e2007-04-24 04:04:35 +00002110 break;
2111 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002112 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002113 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002114 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002115 if (CurTy->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002116 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
Tim Northover29178a32013-01-22 09:46:31 +00002117 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002118 else if (CurTy->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002119 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
Tim Northover29178a32013-01-22 09:46:31 +00002120 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002121 else if (CurTy->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002122 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002123 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002124 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002125 // Bits are not stored the same way as a normal i80 APInt, compensate.
2126 uint64_t Rearrange[2];
2127 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2128 Rearrange[1] = Record[0] >> 48;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002129 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
Tim Northover29178a32013-01-22 09:46:31 +00002130 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002131 } else if (CurTy->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002132 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
Tim Northover29178a32013-01-22 09:46:31 +00002133 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002134 else if (CurTy->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002135 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002136 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002137 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002138 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002139 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002140 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002141
Chris Lattnere14cb882007-05-04 19:11:41 +00002142 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2143 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002144 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002145
Chris Lattnere14cb882007-05-04 19:11:41 +00002146 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002147 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002148
Chris Lattner229907c2011-07-18 04:54:35 +00002149 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002150 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002151 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002152 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002153 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002154 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2155 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002156 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002157 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002158 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002159 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2160 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002161 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002162 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002163 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002164 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002165 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002166 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002167 break;
2168 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002169 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002170 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2171 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002172 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002173
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002174 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002175 V = ConstantDataArray::getString(Context, Elts,
2176 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002177 break;
2178 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002179 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2180 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002181 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002182
Chris Lattner372dd1e2012-01-30 00:51:16 +00002183 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002184 if (EltTy->isIntegerTy(8)) {
2185 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2186 if (isa<VectorType>(CurTy))
2187 V = ConstantDataVector::get(Context, Elts);
2188 else
2189 V = ConstantDataArray::get(Context, Elts);
2190 } else if (EltTy->isIntegerTy(16)) {
2191 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2192 if (isa<VectorType>(CurTy))
2193 V = ConstantDataVector::get(Context, Elts);
2194 else
2195 V = ConstantDataArray::get(Context, Elts);
2196 } else if (EltTy->isIntegerTy(32)) {
2197 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2198 if (isa<VectorType>(CurTy))
2199 V = ConstantDataVector::get(Context, Elts);
2200 else
2201 V = ConstantDataArray::get(Context, Elts);
2202 } else if (EltTy->isIntegerTy(64)) {
2203 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2204 if (isa<VectorType>(CurTy))
2205 V = ConstantDataVector::get(Context, Elts);
2206 else
2207 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002208 } else if (EltTy->isHalfTy()) {
2209 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2210 if (isa<VectorType>(CurTy))
2211 V = ConstantDataVector::getFP(Context, Elts);
2212 else
2213 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002214 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002215 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002216 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002217 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002218 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002219 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002220 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002221 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002222 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002223 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002224 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002225 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002226 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002227 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002228 }
2229 break;
2230 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002231 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002232 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002233 return error("Invalid record");
2234 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002235 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002236 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002237 } else {
2238 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2239 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002240 unsigned Flags = 0;
2241 if (Record.size() >= 4) {
2242 if (Opc == Instruction::Add ||
2243 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002244 Opc == Instruction::Mul ||
2245 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002246 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2247 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2248 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2249 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002250 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002251 Opc == Instruction::UDiv ||
2252 Opc == Instruction::LShr ||
2253 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002254 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002255 Flags |= SDivOperator::IsExact;
2256 }
2257 }
2258 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002259 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002260 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002262 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002263 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002264 return error("Invalid record");
2265 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002266 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002267 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002268 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002269 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002270 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002271 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002272 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002273 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2274 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002275 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002276 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002277 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002278 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2279 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2280 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2281 // operands]
David Blaikieb9263572015-03-13 21:03:36 +00002282 unsigned OpNum = 0;
2283 Type *PointeeType = nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +00002284 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2285 Record.size() % 2)
David Blaikieb9263572015-03-13 21:03:36 +00002286 PointeeType = getTypeByID(Record[OpNum++]);
Peter Collingbourned93620b2016-11-10 22:34:55 +00002287
2288 bool InBounds = false;
2289 Optional<unsigned> InRangeIndex;
2290 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2291 uint64_t Op = Record[OpNum++];
2292 InBounds = Op & 1;
2293 InRangeIndex = Op >> 1;
2294 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2295 InBounds = true;
2296
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002297 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002298 while (OpNum != Record.size()) {
2299 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002300 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002301 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002302 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002303 }
David Blaikieb9263572015-03-13 21:03:36 +00002304
David Blaikieb9263572015-03-13 21:03:36 +00002305 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002306 PointeeType !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00002307 cast<PointerType>(Elts[0]->getType()->getScalarType())
David Blaikie4a2e73b2015-04-02 18:55:32 +00002308 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002309 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002310 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002311
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00002312 if (Elts.size() < 1)
2313 return error("Invalid gep with no operands");
2314
David Blaikie4a2e73b2015-04-02 18:55:32 +00002315 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2316 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002317 InBounds, InRangeIndex);
Chris Lattner890683d2007-04-24 18:15:21 +00002318 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002319 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002320 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002321 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002322 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002323
2324 Type *SelectorTy = Type::getInt1Ty(Context);
2325
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002326 // The selector might be an i1 or an <n x i1>
2327 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002328 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002329 if (Value *V = ValueList[Record[0]])
2330 if (SelectorTy != V->getType())
2331 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002332
2333 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2334 SelectorTy),
2335 ValueList.getConstantFwdRef(Record[1],CurTy),
2336 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002337 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002338 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002339 case bitc::CST_CODE_CE_EXTRACTELT
2340 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002341 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002342 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002343 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002344 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002345 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002346 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002347 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002348 Constant *Op1 = nullptr;
2349 if (Record.size() == 4) {
2350 Type *IdxTy = getTypeByID(Record[2]);
2351 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002352 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002353 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2354 } else // TODO: Remove with llvm 4.0
2355 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2356 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002357 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002358 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002359 break;
2360 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002361 case bitc::CST_CODE_CE_INSERTELT
2362 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002363 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002364 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002365 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002366 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2367 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2368 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002369 Constant *Op2 = nullptr;
2370 if (Record.size() == 4) {
2371 Type *IdxTy = getTypeByID(Record[2]);
2372 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002373 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002374 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2375 } else // TODO: Remove with llvm 4.0
2376 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2377 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002378 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002379 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002380 break;
2381 }
2382 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002383 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002384 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002385 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002386 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2387 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002388 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002389 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002390 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002391 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002392 break;
2393 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002394 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002395 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2396 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002397 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002398 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002399 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002400 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2401 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002402 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002403 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002404 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002405 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002406 break;
2407 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002408 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002409 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002410 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002411 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002412 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002413 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002414 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2415 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2416
Duncan Sands9dff9be2010-02-15 16:12:20 +00002417 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002418 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002419 else
Owen Anderson487375e2009-07-29 18:55:55 +00002420 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002421 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002422 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002423 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002424 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002425 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002426 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002427 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002428 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002429 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002430 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002431 unsigned AsmStrSize = Record[1];
2432 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002433 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002434 unsigned ConstStrSize = Record[2+AsmStrSize];
2435 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002436 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002437
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002438 for (unsigned i = 0; i != AsmStrSize; ++i)
2439 AsmStr += (char)Record[2+i];
2440 for (unsigned i = 0; i != ConstStrSize; ++i)
2441 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002442 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002443 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002444 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002445 break;
2446 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002447 // This version adds support for the asm dialect keywords (e.g.,
2448 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002449 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002450 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002451 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002452 std::string AsmStr, ConstrStr;
2453 bool HasSideEffects = Record[0] & 1;
2454 bool IsAlignStack = (Record[0] >> 1) & 1;
2455 unsigned AsmDialect = Record[0] >> 2;
2456 unsigned AsmStrSize = Record[1];
2457 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002458 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002459 unsigned ConstStrSize = Record[2+AsmStrSize];
2460 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002461 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002462
2463 for (unsigned i = 0; i != AsmStrSize; ++i)
2464 AsmStr += (char)Record[2+i];
2465 for (unsigned i = 0; i != ConstStrSize; ++i)
2466 ConstrStr += (char)Record[3+AsmStrSize+i];
2467 PointerType *PTy = cast<PointerType>(CurTy);
2468 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2469 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002470 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002471 break;
2472 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002473 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002474 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002475 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002476 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002477 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002478 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002479 Function *Fn =
2480 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002481 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002482 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002483
2484 // If the function is already parsed we can insert the block address right
2485 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002486 BasicBlock *BB;
2487 unsigned BBID = Record[2];
2488 if (!BBID)
2489 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002490 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002491 if (!Fn->empty()) {
2492 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002493 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002494 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002495 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002496 ++BBI;
2497 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00002498 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002499 } else {
2500 // Otherwise insert a placeholder and remember it so it can be inserted
2501 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002502 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2503 if (FwdBBs.empty())
2504 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002505 if (FwdBBs.size() < BBID + 1)
2506 FwdBBs.resize(BBID + 1);
2507 if (!FwdBBs[BBID])
2508 FwdBBs[BBID] = BasicBlock::Create(Context);
2509 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002510 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002511 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002512 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002513 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002514 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002515
David Majnemer8a1c45d2015-12-12 05:38:55 +00002516 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002517 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002518 }
2519}
Chris Lattner1314b992007-04-22 06:23:29 +00002520
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002521Error BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002522 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002523 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002524
Chad Rosierca2567b2011-12-07 21:44:12 +00002525 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002526 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00002527
2528 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002529 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002530
Chris Lattner27d38752013-01-20 02:13:19 +00002531 switch (Entry.Kind) {
2532 case BitstreamEntry::SubBlock: // Handled for us already.
2533 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002534 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002535 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002536 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002537 case BitstreamEntry::Record:
2538 // The interesting case.
2539 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002540 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002541
Chad Rosierca2567b2011-12-07 21:44:12 +00002542 // Read a use list record.
2543 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002544 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002545 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002546 default: // Default behavior: unknown type.
2547 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002548 case bitc::USELIST_CODE_BB:
2549 IsBB = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00002550 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002551 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002552 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002553 if (RecordLength < 3)
2554 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002555 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002556 unsigned ID = Record.back();
2557 Record.pop_back();
2558
2559 Value *V;
2560 if (IsBB) {
2561 assert(ID < FunctionBBs.size() && "Basic block not found");
2562 V = FunctionBBs[ID];
2563 } else
2564 V = ValueList[ID];
2565 unsigned NumUses = 0;
2566 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00002567 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002568 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002569 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002570 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002571 }
2572 if (Order.size() != Record.size() || NumUses > Record.size())
2573 // Mismatches can happen if the functions are being materialized lazily
2574 // (out-of-order), or a value has been upgraded.
2575 break;
2576
2577 V->sortUseList([&](const Use &L, const Use &R) {
2578 return Order.lookup(&L) < Order.lookup(&R);
2579 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002580 break;
2581 }
2582 }
2583 }
2584}
2585
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002586/// When we see the block for metadata, remember where it is and then skip it.
2587/// This lets us lazily deserialize the metadata.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002588Error BitcodeReader::rememberAndSkipMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002589 // Save the current stream state.
2590 uint64_t CurBit = Stream.GetCurrentBitNo();
2591 DeferredMetadataInfo.push_back(CurBit);
2592
2593 // Skip over the block for now.
2594 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002595 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002596 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002597}
2598
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00002599Error BitcodeReader::materializeMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002600 for (uint64_t BitPos : DeferredMetadataInfo) {
2601 // Move the bit stream to the saved position.
2602 Stream.JumpToBit(BitPos);
Mehdi Aminief27db82016-12-12 19:34:26 +00002603 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002604 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002605 }
2606 DeferredMetadataInfo.clear();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002607 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002608}
2609
Rafael Espindola468b8682015-04-01 14:44:59 +00002610void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002611
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002612/// When we see the block for a function body, remember where it is and then
2613/// skip it. This lets us lazily deserialize the functions.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002614Error BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002615 // Get the function we are talking about.
2616 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002617 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002618
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002619 Function *Fn = FunctionsWithBodies.back();
2620 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002621
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002622 // Save the current stream state.
2623 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00002624 assert(
2625 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2626 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002627 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002628
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002629 // Skip over the function block for now.
2630 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002631 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002632 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002633}
2634
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002635Error BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002636 // Patch the initializers for globals and aliases up.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002637 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2638 return Err;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002639 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002640 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002641
2642 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002643 for (Function &F : *TheModule) {
Adrian Prantl6825fb62017-04-18 01:21:53 +00002644 MDLoader->upgradeDebugIntrinsics(F);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002645 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002646 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00002647 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00002648 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2649 // Some types could be renamed during loading if several modules are
2650 // loaded in the same LLVMContext (LTO scenario). In this case we should
2651 // remangle intrinsics names as well.
2652 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002653 }
2654
2655 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002656 for (GlobalVariable &GV : TheModule->globals())
2657 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002658
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002659 // Force deallocation of memory for these vectors to favor the client that
2660 // want lazy deserialization.
2661 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002662 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
2663 IndirectSymbolInits);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002664 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002665}
2666
Teresa Johnson1493ad92015-10-10 14:18:36 +00002667/// Support for lazy parsing of function bodies. This is required if we
2668/// either have an old bitcode file without a VST forward declaration record,
2669/// or if we have an anonymous function being materialized, since anonymous
2670/// functions do not have a name and are therefore not in the VST.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002671Error BitcodeReader::rememberAndSkipFunctionBodies() {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002672 Stream.JumpToBit(NextUnreadBit);
2673
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002674 if (Stream.AtEndOfStream())
2675 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00002676
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00002677 if (!SeenFirstFunctionBody)
2678 return error("Trying to materialize functions before seeing function blocks");
2679
Teresa Johnson1493ad92015-10-10 14:18:36 +00002680 // An old bitcode file with the symbol table at the end would have
2681 // finished the parse greedily.
2682 assert(SeenValueSymbolTable);
2683
2684 SmallVector<uint64_t, 64> Record;
2685
Eugene Zelenko1804a772016-08-25 00:45:04 +00002686 while (true) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002687 BitstreamEntry Entry = Stream.advance();
2688 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002689 default:
2690 return error("Expect SubBlock");
2691 case BitstreamEntry::SubBlock:
2692 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002693 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002694 return error("Expect function block");
2695 case bitc::FUNCTION_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002696 if (Error Err = rememberAndSkipFunctionBody())
2697 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002698 NextUnreadBit = Stream.GetCurrentBitNo();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002699 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002700 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00002701 }
2702 }
2703}
2704
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002705bool BitcodeReaderBase::readBlockInfo() {
Peter Collingbourne77c89b62016-11-08 04:17:11 +00002706 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2707 if (!NewBlockInfo)
2708 return true;
2709 BlockInfo = std::move(*NewBlockInfo);
2710 return false;
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002711}
2712
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002713Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002714 // v1: [selection_kind, name]
2715 // v2: [strtab_offset, strtab_size, selection_kind]
2716 StringRef Name;
2717 std::tie(Name, Record) = readNameFromStrtab(Record);
2718
2719 if (Record.size() < 1)
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002720 return error("Invalid record");
2721 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002722 std::string OldFormatName;
2723 if (!UseStrtab) {
2724 if (Record.size() < 2)
2725 return error("Invalid record");
2726 unsigned ComdatNameSize = Record[1];
2727 OldFormatName.reserve(ComdatNameSize);
2728 for (unsigned i = 0; i != ComdatNameSize; ++i)
2729 OldFormatName += (char)Record[2 + i];
2730 Name = OldFormatName;
2731 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002732 Comdat *C = TheModule->getOrInsertComdat(Name);
2733 C->setSelectionKind(SK);
2734 ComdatList.push_back(C);
2735 return Error::success();
2736}
2737
2738Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002739 // v1: [pointer type, isconst, initid, linkage, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002740 // visibility, threadlocal, unnamed_addr, externally_initialized,
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002741 // dllstorageclass, comdat] (name in VST)
2742 // v2: [strtab_offset, strtab_size, v1]
2743 StringRef Name;
2744 std::tie(Name, Record) = readNameFromStrtab(Record);
2745
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002746 if (Record.size() < 6)
2747 return error("Invalid record");
2748 Type *Ty = getTypeByID(Record[0]);
2749 if (!Ty)
2750 return error("Invalid record");
2751 bool isConstant = Record[1] & 1;
2752 bool explicitType = Record[1] & 2;
2753 unsigned AddressSpace;
2754 if (explicitType) {
2755 AddressSpace = Record[1] >> 2;
2756 } else {
2757 if (!Ty->isPointerTy())
2758 return error("Invalid type for value");
2759 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2760 Ty = cast<PointerType>(Ty)->getElementType();
2761 }
2762
2763 uint64_t RawLinkage = Record[3];
2764 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2765 unsigned Alignment;
2766 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2767 return Err;
2768 std::string Section;
2769 if (Record[5]) {
2770 if (Record[5] - 1 >= SectionTable.size())
2771 return error("Invalid ID");
2772 Section = SectionTable[Record[5] - 1];
2773 }
2774 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2775 // Local linkage must have default visibility.
2776 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2777 // FIXME: Change to an error if non-default in 4.0.
2778 Visibility = getDecodedVisibility(Record[6]);
2779
2780 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2781 if (Record.size() > 7)
2782 TLM = getDecodedThreadLocalMode(Record[7]);
2783
2784 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2785 if (Record.size() > 8)
2786 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2787
2788 bool ExternallyInitialized = false;
2789 if (Record.size() > 9)
2790 ExternallyInitialized = Record[9];
2791
2792 GlobalVariable *NewGV =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002793 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002794 nullptr, TLM, AddressSpace, ExternallyInitialized);
2795 NewGV->setAlignment(Alignment);
2796 if (!Section.empty())
2797 NewGV->setSection(Section);
2798 NewGV->setVisibility(Visibility);
2799 NewGV->setUnnamedAddr(UnnamedAddr);
2800
2801 if (Record.size() > 10)
2802 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2803 else
2804 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2805
2806 ValueList.push_back(NewGV);
2807
2808 // Remember which value to use for the global initializer.
2809 if (unsigned InitID = Record[2])
2810 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2811
2812 if (Record.size() > 11) {
2813 if (unsigned ComdatID = Record[11]) {
2814 if (ComdatID > ComdatList.size())
2815 return error("Invalid global variable comdat ID");
2816 NewGV->setComdat(ComdatList[ComdatID - 1]);
2817 }
2818 } else if (hasImplicitComdat(RawLinkage)) {
2819 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2820 }
2821 return Error::success();
2822}
2823
2824Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002825 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002826 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002827 // prefixdata] (name in VST)
2828 // v2: [strtab_offset, strtab_size, v1]
2829 StringRef Name;
2830 std::tie(Name, Record) = readNameFromStrtab(Record);
2831
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002832 if (Record.size() < 8)
2833 return error("Invalid record");
2834 Type *Ty = getTypeByID(Record[0]);
2835 if (!Ty)
2836 return error("Invalid record");
2837 if (auto *PTy = dyn_cast<PointerType>(Ty))
2838 Ty = PTy->getElementType();
2839 auto *FTy = dyn_cast<FunctionType>(Ty);
2840 if (!FTy)
2841 return error("Invalid type for value");
2842 auto CC = static_cast<CallingConv::ID>(Record[1]);
2843 if (CC & ~CallingConv::MaxID)
2844 return error("Invalid calling convention ID");
2845
2846 Function *Func =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002847 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002848
2849 Func->setCallingConv(CC);
2850 bool isProto = Record[2];
2851 uint64_t RawLinkage = Record[3];
2852 Func->setLinkage(getDecodedLinkage(RawLinkage));
2853 Func->setAttributes(getAttributes(Record[4]));
2854
2855 unsigned Alignment;
2856 if (Error Err = parseAlignmentValue(Record[5], Alignment))
2857 return Err;
2858 Func->setAlignment(Alignment);
2859 if (Record[6]) {
2860 if (Record[6] - 1 >= SectionTable.size())
2861 return error("Invalid ID");
2862 Func->setSection(SectionTable[Record[6] - 1]);
2863 }
2864 // Local linkage must have default visibility.
2865 if (!Func->hasLocalLinkage())
2866 // FIXME: Change to an error if non-default in 4.0.
2867 Func->setVisibility(getDecodedVisibility(Record[7]));
2868 if (Record.size() > 8 && Record[8]) {
2869 if (Record[8] - 1 >= GCTable.size())
2870 return error("Invalid ID");
2871 Func->setGC(GCTable[Record[8] - 1]);
2872 }
2873 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2874 if (Record.size() > 9)
2875 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2876 Func->setUnnamedAddr(UnnamedAddr);
2877 if (Record.size() > 10 && Record[10] != 0)
2878 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2879
2880 if (Record.size() > 11)
2881 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2882 else
2883 upgradeDLLImportExportLinkage(Func, RawLinkage);
2884
2885 if (Record.size() > 12) {
2886 if (unsigned ComdatID = Record[12]) {
2887 if (ComdatID > ComdatList.size())
2888 return error("Invalid function comdat ID");
2889 Func->setComdat(ComdatList[ComdatID - 1]);
2890 }
2891 } else if (hasImplicitComdat(RawLinkage)) {
2892 Func->setComdat(reinterpret_cast<Comdat *>(1));
2893 }
2894
2895 if (Record.size() > 13 && Record[13] != 0)
2896 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2897
2898 if (Record.size() > 14 && Record[14] != 0)
2899 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2900
2901 ValueList.push_back(Func);
2902
2903 // If this is a function with a body, remember the prototype we are
2904 // creating now, so that we can match up the body with them later.
2905 if (!isProto) {
2906 Func->setIsMaterializable(true);
2907 FunctionsWithBodies.push_back(Func);
2908 DeferredFunctionInfo[Func] = 0;
2909 }
2910 return Error::success();
2911}
2912
2913Error BitcodeReader::parseGlobalIndirectSymbolRecord(
2914 unsigned BitCode, ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002915 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
2916 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
2917 // dllstorageclass] (name in VST)
2918 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
2919 // visibility, dllstorageclass] (name in VST)
2920 // v2: [strtab_offset, strtab_size, v1]
2921 StringRef Name;
2922 std::tie(Name, Record) = readNameFromStrtab(Record);
2923
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002924 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
2925 if (Record.size() < (3 + (unsigned)NewRecord))
2926 return error("Invalid record");
2927 unsigned OpNum = 0;
2928 Type *Ty = getTypeByID(Record[OpNum++]);
2929 if (!Ty)
2930 return error("Invalid record");
2931
2932 unsigned AddrSpace;
2933 if (!NewRecord) {
2934 auto *PTy = dyn_cast<PointerType>(Ty);
2935 if (!PTy)
2936 return error("Invalid type for value");
2937 Ty = PTy->getElementType();
2938 AddrSpace = PTy->getAddressSpace();
2939 } else {
2940 AddrSpace = Record[OpNum++];
2941 }
2942
2943 auto Val = Record[OpNum++];
2944 auto Linkage = Record[OpNum++];
2945 GlobalIndirectSymbol *NewGA;
2946 if (BitCode == bitc::MODULE_CODE_ALIAS ||
2947 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002948 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002949 TheModule);
2950 else
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002951 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002952 nullptr, TheModule);
2953 // Old bitcode files didn't have visibility field.
2954 // Local linkage must have default visibility.
2955 if (OpNum != Record.size()) {
2956 auto VisInd = OpNum++;
2957 if (!NewGA->hasLocalLinkage())
2958 // FIXME: Change to an error if non-default in 4.0.
2959 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
2960 }
2961 if (OpNum != Record.size())
2962 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
2963 else
2964 upgradeDLLImportExportLinkage(NewGA, Linkage);
2965 if (OpNum != Record.size())
2966 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
2967 if (OpNum != Record.size())
2968 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
2969 ValueList.push_back(NewGA);
2970 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
2971 return Error::success();
2972}
2973
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002974Error BitcodeReader::parseModule(uint64_t ResumeBit,
2975 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002976 if (ResumeBit)
2977 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002978 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002979 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002980
Chris Lattner1314b992007-04-22 06:23:29 +00002981 SmallVector<uint64_t, 64> Record;
Chris Lattner1314b992007-04-22 06:23:29 +00002982
2983 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00002984 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002985 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002986
Chris Lattner27d38752013-01-20 02:13:19 +00002987 switch (Entry.Kind) {
2988 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002989 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002990 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002991 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00002992
Chris Lattner27d38752013-01-20 02:13:19 +00002993 case BitstreamEntry::SubBlock:
2994 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00002995 default: // Skip unknown content.
2996 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002997 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002998 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002999 case bitc::BLOCKINFO_BLOCK_ID:
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003000 if (readBlockInfo())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003001 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003002 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003003 case bitc::PARAMATTR_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003004 if (Error Err = parseAttributeBlock())
3005 return Err;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003006 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003007 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003008 if (Error Err = parseAttributeGroupBlock())
3009 return Err;
Bill Wendlingba629332013-02-10 23:24:25 +00003010 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003011 case bitc::TYPE_BLOCK_ID_NEW:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003012 if (Error Err = parseTypeTable())
3013 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003014 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003015 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003016 if (!SeenValueSymbolTable) {
3017 // Either this is an old form VST without function index and an
3018 // associated VST forward declaration record (which would have caused
3019 // the VST to be jumped to and parsed before it was encountered
3020 // normally in the stream), or there were no function blocks to
3021 // trigger an earlier parsing of the VST.
3022 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003023 if (Error Err = parseValueSymbolTable())
3024 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003025 SeenValueSymbolTable = true;
3026 } else {
3027 // We must have had a VST forward declaration record, which caused
3028 // the parser to jump to and parse the VST earlier.
3029 assert(VSTOffset > 0);
3030 if (Stream.SkipBlock())
3031 return error("Invalid record");
3032 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003033 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003034 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003035 if (Error Err = parseConstants())
3036 return Err;
3037 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3038 return Err;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003039 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003040 case bitc::METADATA_BLOCK_ID:
Mehdi Aminibf2090e2016-12-12 19:23:39 +00003041 if (ShouldLazyLoadMetadata) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003042 if (Error Err = rememberAndSkipMetadata())
3043 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003044 break;
3045 }
3046 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Mehdi Aminief27db82016-12-12 19:34:26 +00003047 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003048 return Err;
Devang Patel7428d8a2009-07-22 17:43:22 +00003049 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003050 case bitc::METADATA_KIND_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003051 if (Error Err = MDLoader->parseMetadataKinds())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003052 return Err;
Teresa Johnson12545072015-11-15 02:00:09 +00003053 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003054 case bitc::FUNCTION_BLOCK_ID:
Mehdi Amini466a64e2016-08-13 23:39:14 +00003055 // If this is the first function body we've seen, reverse the
3056 // FunctionsWithBodies list.
3057 if (!SeenFirstFunctionBody) {
3058 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003059 if (Error Err = globalCleanup())
3060 return Err;
Mehdi Amini466a64e2016-08-13 23:39:14 +00003061 SeenFirstFunctionBody = true;
3062 }
3063
Teresa Johnsonff642b92015-09-17 20:12:00 +00003064 if (VSTOffset > 0) {
3065 // If we have a VST forward declaration record, make sure we
3066 // parse the VST now if we haven't already. It is needed to
3067 // set up the DeferredFunctionInfo vector for lazy reading.
3068 if (!SeenValueSymbolTable) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003069 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3070 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003071 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003072 // Fall through so that we record the NextUnreadBit below.
3073 // This is necessary in case we have an anonymous function that
3074 // is later materialized. Since it will not have a VST entry we
3075 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003076 } else {
3077 // If we have a VST forward declaration record, but have already
3078 // parsed the VST (just above, when the first function body was
3079 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003080 // materializing functions. The ResumeBit points to the
3081 // start of the last function block recorded in the
3082 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003083 if (Stream.SkipBlock())
3084 return error("Invalid record");
3085 continue;
3086 }
3087 }
3088
3089 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003090 // index in the VST, nor a VST forward declaration record, as
3091 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003092 // Build the DeferredFunctionInfo vector on the fly.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003093 if (Error Err = rememberAndSkipFunctionBody())
3094 return Err;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003095
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003096 // Suspend parsing when we reach the function bodies. Subsequent
3097 // materialization calls will resume it when necessary. If the bitcode
3098 // file is old, the symbol table will be at the end instead and will not
3099 // have been seen yet. In this case, just finish the parse now.
3100 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003101 NextUnreadBit = Stream.GetCurrentBitNo();
Mehdi Aminia71002e2016-08-14 00:01:27 +00003102 // After the VST has been parsed, we need to make sure intrinsic name
3103 // are auto-upgraded.
3104 return globalCleanup();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003105 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003106 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003107 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003108 if (Error Err = parseUseLists())
3109 return Err;
Chad Rosierca2567b2011-12-07 21:44:12 +00003110 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003111 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003112 if (Error Err = parseOperandBundleTags())
3113 return Err;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003114 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003115 }
3116 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003117
Chris Lattner27d38752013-01-20 02:13:19 +00003118 case BitstreamEntry::Record:
3119 // The interesting case.
3120 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003122
Chris Lattner1314b992007-04-22 06:23:29 +00003123 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003124 auto BitCode = Stream.readRecord(Entry.ID, Record);
3125 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003126 default: break; // Default behavior, ignore unknown content.
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003127 case bitc::MODULE_CODE_VERSION: {
3128 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3129 if (!VersionOrErr)
3130 return VersionOrErr.takeError();
3131 UseRelativeIDs = *VersionOrErr >= 1;
Chris Lattner1314b992007-04-22 06:23:29 +00003132 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003133 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003134 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003135 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003136 if (convertToString(Record, 0, S))
3137 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003138 TheModule->setTargetTriple(S);
3139 break;
3140 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003141 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003142 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003143 if (convertToString(Record, 0, S))
3144 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003145 TheModule->setDataLayout(S);
3146 break;
3147 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003148 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003149 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003150 if (convertToString(Record, 0, S))
3151 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003152 TheModule->setModuleInlineAsm(S);
3153 break;
3154 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003155 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3156 // FIXME: Remove in 4.0.
3157 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003158 if (convertToString(Record, 0, S))
3159 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003160 // Ignore value.
3161 break;
3162 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003163 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003164 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003165 if (convertToString(Record, 0, S))
3166 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003167 SectionTable.push_back(S);
3168 break;
3169 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003170 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003171 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003172 if (convertToString(Record, 0, S))
3173 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003174 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003175 break;
3176 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003177 case bitc::MODULE_CODE_COMDAT: {
3178 if (Error Err = parseComdatRecord(Record))
3179 return Err;
David Majnemerdad0a642014-06-27 18:19:56 +00003180 break;
3181 }
Chris Lattner1314b992007-04-22 06:23:29 +00003182 case bitc::MODULE_CODE_GLOBALVAR: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003183 if (Error Err = parseGlobalVarRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003184 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003185 break;
3186 }
Chris Lattner1314b992007-04-22 06:23:29 +00003187 case bitc::MODULE_CODE_FUNCTION: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003188 if (Error Err = parseFunctionRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003189 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003190 break;
3191 }
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003192 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003193 case bitc::MODULE_CODE_ALIAS:
3194 case bitc::MODULE_CODE_ALIAS_OLD: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003195 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3196 return Err;
Chris Lattner44c17072007-04-26 02:46:40 +00003197 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003198 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00003199 /// MODULE_CODE_VSTOFFSET: [offset]
3200 case bitc::MODULE_CODE_VSTOFFSET:
3201 if (Record.size() < 1)
3202 return error("Invalid record");
Peter Collingbournebfcf9802016-11-29 02:27:04 +00003203 // Note that we subtract 1 here because the offset is relative to one word
3204 // before the start of the identification or module block, which was
3205 // historically always the start of the regular bitcode header.
3206 VSTOffset = Record[0] - 1;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003207 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003208 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3209 case bitc::MODULE_CODE_SOURCE_FILENAME:
3210 SmallString<128> ValueName;
3211 if (convertToString(Record, 0, ValueName))
3212 return error("Invalid record");
3213 TheModule->setSourceFileName(ValueName);
3214 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003215 }
Chris Lattner1314b992007-04-22 06:23:29 +00003216 Record.clear();
3217 }
Chris Lattner1314b992007-04-22 06:23:29 +00003218}
3219
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003220Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3221 bool IsImporting) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003222 TheModule = M;
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003223 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00003224 [&](unsigned ID) { return getTypeByID(ID); });
Peter Collingbourne7a748032016-11-16 21:44:45 +00003225 return parseModule(0, ShouldLazyLoadMetadata);
Chris Lattner1314b992007-04-22 06:23:29 +00003226}
Chris Lattner6694f602007-04-29 07:54:31 +00003227
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003228
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003229Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003230 if (!isa<PointerType>(PtrType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003231 return error("Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003232 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3233
3234 if (ValType && ValType != ElemType)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003235 return error("Explicit load/store type does not match pointee "
3236 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003237 if (!PointerType::isLoadableOrStorableType(ElemType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003238 return error("Cannot load/store from pointer");
3239 return Error::success();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003240}
3241
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003242/// Lazily parse the specified function body block.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003243Error BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003244 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003245 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003246
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003247 // Unexpected unresolved metadata when parsing function.
Mehdi Aminief27db82016-12-12 19:34:26 +00003248 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003249 return error("Invalid function metadata: incoming forward references");
3250
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003251 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003252 unsigned ModuleValueListSize = ValueList.size();
Mehdi Aminief27db82016-12-12 19:34:26 +00003253 unsigned ModuleMDLoaderSize = MDLoader->size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003254
Chris Lattner85b7b402007-05-01 05:52:21 +00003255 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003256 for (Argument &I : F->args())
3257 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003258
Chris Lattner83930552007-05-01 07:01:57 +00003259 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003260 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003261 unsigned CurBBNo = 0;
3262
Chris Lattner07d09ed2010-04-03 02:17:50 +00003263 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003264 auto getLastInstruction = [&]() -> Instruction * {
3265 if (CurBB && !CurBB->empty())
3266 return &CurBB->back();
3267 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3268 !FunctionBBs[CurBBNo - 1]->empty())
3269 return &FunctionBBs[CurBBNo - 1]->back();
3270 return nullptr;
3271 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003272
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003273 std::vector<OperandBundleDef> OperandBundles;
3274
Chris Lattner85b7b402007-05-01 05:52:21 +00003275 // Read all the records.
3276 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00003277
3278 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003279 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003280
Chris Lattner27d38752013-01-20 02:13:19 +00003281 switch (Entry.Kind) {
3282 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003283 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003284 case BitstreamEntry::EndBlock:
3285 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003286
Chris Lattner27d38752013-01-20 02:13:19 +00003287 case BitstreamEntry::SubBlock:
3288 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003289 default: // Skip unknown content.
3290 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003291 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003292 break;
3293 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003294 if (Error Err = parseConstants())
3295 return Err;
Chris Lattner83930552007-05-01 07:01:57 +00003296 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003297 break;
3298 case bitc::VALUE_SYMTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003299 if (Error Err = parseValueSymbolTable())
3300 return Err;
Chris Lattner85b7b402007-05-01 05:52:21 +00003301 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003302 case bitc::METADATA_ATTACHMENT_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003303 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003304 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003305 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003306 case bitc::METADATA_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003307 assert(DeferredMetadataInfo.empty() &&
3308 "Must read all module-level metadata before function-level");
3309 if (Error Err = MDLoader->parseFunctionMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003310 return Err;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003311 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003312 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003313 if (Error Err = parseUseLists())
3314 return Err;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003315 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003316 }
3317 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003318
Chris Lattner27d38752013-01-20 02:13:19 +00003319 case BitstreamEntry::Record:
3320 // The interesting case.
3321 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003322 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003323
Chris Lattner85b7b402007-05-01 05:52:21 +00003324 // Read a record.
3325 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003326 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003327 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003328 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003329 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003330 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003331 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003332 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003333 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003334 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003335 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003336
3337 // See if anything took the address of blocks in this function.
3338 auto BBFRI = BasicBlockFwdRefs.find(F);
3339 if (BBFRI == BasicBlockFwdRefs.end()) {
3340 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3341 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3342 } else {
3343 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003344 // Check for invalid basic block references.
3345 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003346 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003347 assert(!BBRefs.empty() && "Unexpected empty array");
3348 assert(!BBRefs.front() && "Invalid reference to entry block");
3349 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3350 ++I)
3351 if (I < RE && BBRefs[I]) {
3352 BBRefs[I]->insertInto(F);
3353 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003354 } else {
3355 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3356 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003357
3358 // Erase from the table.
3359 BasicBlockFwdRefs.erase(BBFRI);
3360 }
3361
Chris Lattner83930552007-05-01 07:01:57 +00003362 CurBB = FunctionBBs[0];
3363 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003364 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003365
Chris Lattner07d09ed2010-04-03 02:17:50 +00003366 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3367 // This record indicates that the last instruction is at the same
3368 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003369 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003370
Craig Topper2617dcc2014-04-15 06:32:26 +00003371 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003372 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003373 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003374 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003375 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003376
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003377 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003378 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003379 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003380 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003381
Chris Lattner07d09ed2010-04-03 02:17:50 +00003382 unsigned Line = Record[0], Col = Record[1];
3383 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003384
Craig Topper2617dcc2014-04-15 06:32:26 +00003385 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00003386 if (ScopeID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003387 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003388 if (!Scope)
3389 return error("Invalid record");
3390 }
3391 if (IAID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003392 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003393 if (!IA)
3394 return error("Invalid record");
3395 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00003396 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3397 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003398 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003399 continue;
3400 }
3401
Chris Lattnere9759c22007-05-06 00:21:25 +00003402 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3403 unsigned OpNum = 0;
3404 Value *LHS, *RHS;
3405 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003406 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003407 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003408 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003409
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003410 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003411 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003412 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003413 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003414 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003415 if (OpNum < Record.size()) {
3416 if (Opc == Instruction::Add ||
3417 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003418 Opc == Instruction::Mul ||
3419 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003420 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003421 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003422 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003423 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003424 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003425 Opc == Instruction::UDiv ||
3426 Opc == Instruction::LShr ||
3427 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003428 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003429 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003430 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00003431 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003432 if (FMF.any())
3433 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003434 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003435
Dan Gohman1b849082009-09-07 23:54:19 +00003436 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003437 break;
3438 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003439 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3440 unsigned OpNum = 0;
3441 Value *Op;
3442 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3443 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003444 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003445
Chris Lattner229907c2011-07-18 04:54:35 +00003446 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003447 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003448 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003449 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003450 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003451 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3452 if (Temp) {
3453 InstructionList.push_back(Temp);
3454 CurBB->getInstList().push_back(Temp);
3455 }
3456 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00003457 auto CastOp = (Instruction::CastOps)Opc;
3458 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3459 return error("Invalid cast");
3460 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003461 }
Devang Patelaf206b82009-09-18 19:26:43 +00003462 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003463 break;
3464 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003465 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3466 case bitc::FUNC_CODE_INST_GEP_OLD:
3467 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003468 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003469
3470 Type *Ty;
3471 bool InBounds;
3472
3473 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3474 InBounds = Record[OpNum++];
3475 Ty = getTypeByID(Record[OpNum++]);
3476 } else {
3477 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3478 Ty = nullptr;
3479 }
3480
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003481 Value *BasePtr;
3482 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003483 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003484
David Blaikie60310f22015-05-08 00:42:26 +00003485 if (!Ty)
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003486 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003487 ->getElementType();
3488 else if (Ty !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003489 cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003490 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003491 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00003492 "Explicit gep type does not match pointee type of pointer operand");
3493
Chris Lattner5285b5e2007-05-02 05:46:45 +00003494 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003495 while (OpNum != Record.size()) {
3496 Value *Op;
3497 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003498 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003499 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003500 }
3501
David Blaikie096b1da2015-03-14 19:53:33 +00003502 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003503
Devang Patelaf206b82009-09-18 19:26:43 +00003504 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003505 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003506 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003507 break;
3508 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003509
Dan Gohman1ecaf452008-05-31 00:58:22 +00003510 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3511 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003512 unsigned OpNum = 0;
3513 Value *Agg;
3514 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003515 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003516
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003517 unsigned RecSize = Record.size();
3518 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003519 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003520
Dan Gohman1ecaf452008-05-31 00:58:22 +00003521 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003522 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003523 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003524 bool IsArray = CurTy->isArrayTy();
3525 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003526 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003527
3528 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003529 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003530 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003531 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003532 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003533 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003534 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003535 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003536 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003537
3538 if (IsStruct)
3539 CurTy = CurTy->subtypes()[Index];
3540 else
3541 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003542 }
3543
Jay Foad57aa6362011-07-13 10:26:04 +00003544 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003545 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003546 break;
3547 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003548
Dan Gohman1ecaf452008-05-31 00:58:22 +00003549 case bitc::FUNC_CODE_INST_INSERTVAL: {
3550 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003551 unsigned OpNum = 0;
3552 Value *Agg;
3553 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003554 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003555 Value *Val;
3556 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003557 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003558
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003559 unsigned RecSize = Record.size();
3560 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003561 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003562
Dan Gohman1ecaf452008-05-31 00:58:22 +00003563 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003564 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003565 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003566 bool IsArray = CurTy->isArrayTy();
3567 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003568 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003569
3570 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003571 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003572 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003573 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003574 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003575 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003576 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003577 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003578
Dan Gohman1ecaf452008-05-31 00:58:22 +00003579 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003580 if (IsStruct)
3581 CurTy = CurTy->subtypes()[Index];
3582 else
3583 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003584 }
3585
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003586 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003587 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003588
Jay Foad57aa6362011-07-13 10:26:04 +00003589 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003590 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003591 break;
3592 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003593
Chris Lattnere9759c22007-05-06 00:21:25 +00003594 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003595 // obsolete form of select
3596 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003597 unsigned OpNum = 0;
3598 Value *TrueVal, *FalseVal, *Cond;
3599 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003600 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3601 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003602 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003603
Dan Gohmanc5d28922008-09-16 01:01:33 +00003604 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003605 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003606 break;
3607 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003608
Dan Gohmanc5d28922008-09-16 01:01:33 +00003609 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3610 // new form of select
3611 // handles select i1 or select [N x i1]
3612 unsigned OpNum = 0;
3613 Value *TrueVal, *FalseVal, *Cond;
3614 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003615 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003616 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003617 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003618
3619 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003620 if (VectorType* vector_type =
3621 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003622 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003623 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003624 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003625 } else {
3626 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003627 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003628 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003629 }
3630
Gabor Greife9ecc682008-04-06 20:25:17 +00003631 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003632 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003633 break;
3634 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003635
Chris Lattner1fc27f02007-05-02 05:16:49 +00003636 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003637 unsigned OpNum = 0;
3638 Value *Vec, *Idx;
3639 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003640 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003641 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003642 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003643 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003644 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003645 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003646 break;
3647 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003648
Chris Lattner1fc27f02007-05-02 05:16:49 +00003649 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003650 unsigned OpNum = 0;
3651 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003652 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003653 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003654 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003655 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003656 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003657 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003658 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003659 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003660 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003661 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003662 break;
3663 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003664
Chris Lattnere9759c22007-05-06 00:21:25 +00003665 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3666 unsigned OpNum = 0;
3667 Value *Vec1, *Vec2, *Mask;
3668 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003669 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003670 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003671
Mon P Wang25f01062008-11-10 04:46:22 +00003672 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003673 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003674 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003675 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003676 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003677 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003678 break;
3679 }
Mon P Wang25f01062008-11-10 04:46:22 +00003680
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003681 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3682 // Old form of ICmp/FCmp returning bool
3683 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3684 // both legal on vectors but had different behaviour.
3685 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3686 // FCmp/ICmp returning bool or vector of bool
3687
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003688 unsigned OpNum = 0;
3689 Value *LHS, *RHS;
3690 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00003691 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3692 return error("Invalid record");
3693
3694 unsigned PredVal = Record[OpNum];
3695 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3696 FastMathFlags FMF;
3697 if (IsFP && Record.size() > OpNum+1)
3698 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3699
3700 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003701 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003702
Duncan Sands9dff9be2010-02-15 16:12:20 +00003703 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00003704 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003705 else
James Molloy88eb5352015-07-10 12:52:00 +00003706 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3707
3708 if (FMF.any())
3709 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00003710 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003711 break;
3712 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003713
Chris Lattnere53603e2007-05-02 04:27:25 +00003714 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003715 {
3716 unsigned Size = Record.size();
3717 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003718 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003719 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003720 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003721 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003722
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003723 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003724 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003725 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003726 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003727 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003728 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003729
Chris Lattnerf1c87102011-06-17 18:09:11 +00003730 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003731 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003732 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003733 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003734 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003735 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003736 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003737 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003738 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003739 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003740
Devang Patelaf206b82009-09-18 19:26:43 +00003741 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003742 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003743 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003744 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003745 else {
3746 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003747 Value *Cond = getValue(Record, 2, NextValueNo,
3748 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003749 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003750 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003751 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003752 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003753 }
3754 break;
3755 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00003756 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003757 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003758 return error("Invalid record");
3759 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003760 Value *CleanupPad =
3761 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003762 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00003763 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003764 BasicBlock *UnwindDest = nullptr;
3765 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00003766 UnwindDest = getBasicBlock(Record[Idx++]);
3767 if (!UnwindDest)
3768 return error("Invalid record");
3769 }
3770
David Majnemer8a1c45d2015-12-12 05:38:55 +00003771 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00003772 InstructionList.push_back(I);
3773 break;
3774 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003775 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3776 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003777 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003778 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003779 Value *CatchPad =
3780 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003781 if (!CatchPad)
3782 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003783 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00003784 if (!BB)
3785 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003786
David Majnemer8a1c45d2015-12-12 05:38:55 +00003787 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00003788 InstructionList.push_back(I);
3789 break;
3790 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003791 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3792 // We must have, at minimum, the outer scope and the number of arguments.
3793 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003794 return error("Invalid record");
3795
David Majnemer654e1302015-07-31 17:58:14 +00003796 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003797
3798 Value *ParentPad =
3799 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3800
3801 unsigned NumHandlers = Record[Idx++];
3802
3803 SmallVector<BasicBlock *, 2> Handlers;
3804 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3805 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3806 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00003807 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003808 Handlers.push_back(BB);
3809 }
3810
3811 BasicBlock *UnwindDest = nullptr;
3812 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00003813 UnwindDest = getBasicBlock(Record[Idx++]);
3814 if (!UnwindDest)
3815 return error("Invalid record");
3816 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003817
3818 if (Record.size() != Idx)
3819 return error("Invalid record");
3820
3821 auto *CatchSwitch =
3822 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3823 for (BasicBlock *Handler : Handlers)
3824 CatchSwitch->addHandler(Handler);
3825 I = CatchSwitch;
3826 InstructionList.push_back(I);
3827 break;
3828 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003829 case bitc::FUNC_CODE_INST_CATCHPAD:
3830 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3831 // We must have, at minimum, the outer scope and the number of arguments.
3832 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003833 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003834
David Majnemer654e1302015-07-31 17:58:14 +00003835 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003836
3837 Value *ParentPad =
3838 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3839
David Majnemer654e1302015-07-31 17:58:14 +00003840 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00003841
David Majnemer654e1302015-07-31 17:58:14 +00003842 SmallVector<Value *, 2> Args;
3843 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3844 Value *Val;
3845 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3846 return error("Invalid record");
3847 Args.push_back(Val);
3848 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003849
David Majnemer654e1302015-07-31 17:58:14 +00003850 if (Record.size() != Idx)
3851 return error("Invalid record");
3852
David Majnemer8a1c45d2015-12-12 05:38:55 +00003853 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3854 I = CleanupPadInst::Create(ParentPad, Args);
3855 else
3856 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003857 InstructionList.push_back(I);
3858 break;
3859 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003860 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003861 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003862 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003863 // "New" SwitchInst format with case ranges. The changes to write this
3864 // format were reverted but we still recognize bitcode that uses it.
3865 // Hopefully someday we will have support for case ranges and can use
3866 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003867
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003868 Type *OpTy = getTypeByID(Record[1]);
3869 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3870
Jan Wen Voungafaced02012-10-11 20:20:40 +00003871 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003872 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003873 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003874 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003875
3876 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003877
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003878 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3879 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003880
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003881 unsigned CurIdx = 5;
3882 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003883 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003884 unsigned NumItems = Record[CurIdx++];
3885 for (unsigned ci = 0; ci != NumItems; ++ci) {
3886 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003887
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003888 APInt Low;
3889 unsigned ActiveWords = 1;
3890 if (ValueBitWidth > 64)
3891 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003892 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003893 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003894 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003895
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003896 if (!isSingleNumber) {
3897 ActiveWords = 1;
3898 if (ValueBitWidth > 64)
3899 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003900 APInt High = readWideAPInt(
3901 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003902 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003903
3904 // FIXME: It is not clear whether values in the range should be
3905 // compared as signed or unsigned values. The partially
3906 // implemented changes that used this format in the past used
3907 // unsigned comparisons.
3908 for ( ; Low.ule(High); ++Low)
3909 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003910 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003911 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003912 }
3913 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00003914 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3915 cve = CaseVals.end(); cvi != cve; ++cvi)
3916 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003917 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003918 I = SI;
3919 break;
3920 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003921
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003922 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003923
Chris Lattner5285b5e2007-05-02 05:46:45 +00003924 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003925 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003926 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003927 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003928 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003929 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003930 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003931 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00003932 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00003933 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003934 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003935 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00003936 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3937 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003938 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00003939 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003940 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003941 }
3942 SI->addCase(CaseVal, DestBB);
3943 }
3944 I = SI;
3945 break;
3946 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003947 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00003948 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003949 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003950 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003951 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003952 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003953 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003954 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003955 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00003956 InstructionList.push_back(IBI);
3957 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3958 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3959 IBI->addDestination(DestBB);
3960 } else {
3961 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003962 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003963 }
3964 }
3965 I = IBI;
3966 break;
3967 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003968
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003969 case bitc::FUNC_CODE_INST_INVOKE: {
3970 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003971 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003972 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003973 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00003974 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003975 unsigned CCInfo = Record[OpNum++];
3976 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3977 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003978
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003979 FunctionType *FTy = nullptr;
3980 if (CCInfo >> 13 & 1 &&
3981 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003982 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003983
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003984 Value *Callee;
3985 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003986 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003987
Chris Lattner229907c2011-07-18 04:54:35 +00003988 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003989 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003990 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003991 if (!FTy) {
3992 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3993 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003994 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003995 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003996 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003997 "callee operand");
3998 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003999 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004000
Chris Lattner5285b5e2007-05-02 05:46:45 +00004001 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004002 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004003 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4004 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004005 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004006 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004007 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004008
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004009 if (!FTy->isVarArg()) {
4010 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004011 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004012 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004013 // Read type/value pairs for varargs params.
4014 while (OpNum != Record.size()) {
4015 Value *Op;
4016 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004017 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004018 Ops.push_back(Op);
4019 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004020 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004021
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004022 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4023 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004024 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004025 cast<InvokeInst>(I)->setCallingConv(
4026 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004027 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004028 break;
4029 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004030 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4031 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004032 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004033 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004034 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004035 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004036 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004037 break;
4038 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004039 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004040 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004041 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004042 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004043 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004044 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004045 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004046 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004047 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004048 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004049
Jay Foad52131342011-03-30 11:28:46 +00004050 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004051 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004052
Chris Lattnere14cb882007-05-04 19:11:41 +00004053 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004054 Value *V;
4055 // With the new function encoding, it is possible that operands have
4056 // negative IDs (for forward references). Use a signed VBR
4057 // representation to keep the encoding small.
4058 if (UseRelativeIDs)
4059 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4060 else
4061 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004062 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004063 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004064 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004065 PN->addIncoming(V, BB);
4066 }
4067 I = PN;
4068 break;
4069 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004070
David Majnemer7fddecc2015-06-17 20:52:32 +00004071 case bitc::FUNC_CODE_INST_LANDINGPAD:
4072 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004073 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4074 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004075 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4076 if (Record.size() < 3)
4077 return error("Invalid record");
4078 } else {
4079 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4080 if (Record.size() < 4)
4081 return error("Invalid record");
4082 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004083 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004084 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004085 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004086 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4087 Value *PersFn = nullptr;
4088 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4089 return error("Invalid record");
4090
4091 if (!F->hasPersonalityFn())
4092 F->setPersonalityFn(cast<Constant>(PersFn));
4093 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4094 return error("Personality function mismatch");
4095 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004096
4097 bool IsCleanup = !!Record[Idx++];
4098 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004099 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004100 LP->setCleanup(IsCleanup);
4101 for (unsigned J = 0; J != NumClauses; ++J) {
4102 LandingPadInst::ClauseType CT =
4103 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4104 Value *Val;
4105
4106 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4107 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004108 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004109 }
4110
4111 assert((CT != LandingPadInst::Catch ||
4112 !isa<ArrayType>(Val->getType())) &&
4113 "Catch clause has a invalid type!");
4114 assert((CT != LandingPadInst::Filter ||
4115 isa<ArrayType>(Val->getType())) &&
4116 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004117 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004118 }
4119
4120 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004121 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004122 break;
4123 }
4124
Chris Lattnerf1c87102011-06-17 18:09:11 +00004125 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4126 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004127 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004128 uint64_t AlignRecord = Record[3];
4129 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004130 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004131 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4132 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4133 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004134 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004135 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004136 Type *Ty = getTypeByID(Record[0]);
4137 if ((AlignRecord & ExplicitTypeMask) == 0) {
4138 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4139 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004140 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004141 Ty = PTy->getElementType();
4142 }
4143 Type *OpTy = getTypeByID(Record[1]);
4144 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004145 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004146 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4147 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004148 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004149 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004150 return error("Invalid record");
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004151
4152 // FIXME: Make this an optional field.
4153 const DataLayout &DL = TheModule->getDataLayout();
4154 unsigned AS = DL.getAllocaAddrSpace();
4155
4156 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004157 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00004158 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004159 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004160 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004161 break;
4162 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004163 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004164 unsigned OpNum = 0;
4165 Value *Op;
4166 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004167 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004168 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004169
4170 Type *Ty = nullptr;
4171 if (OpNum + 3 == Record.size())
4172 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004173 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4174 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004175 if (!Ty)
4176 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004177
JF Bastien30bf96b2015-02-22 19:32:03 +00004178 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004179 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4180 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004181 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004182
Devang Patelaf206b82009-09-18 19:26:43 +00004183 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004184 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004185 }
Eli Friedman59b66882011-08-09 23:02:53 +00004186 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4187 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4188 unsigned OpNum = 0;
4189 Value *Op;
4190 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004191 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004192 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004193
David Blaikie85035652015-02-25 01:07:20 +00004194 Type *Ty = nullptr;
4195 if (OpNum + 5 == Record.size())
4196 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004197 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4198 return Err;
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004199 if (!Ty)
4200 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004201
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004202 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004203 if (Ordering == AtomicOrdering::NotAtomic ||
4204 Ordering == AtomicOrdering::Release ||
4205 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004206 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00004207 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004208 return error("Invalid record");
4209 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004210
JF Bastien30bf96b2015-02-22 19:32:03 +00004211 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004212 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4213 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004214 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004215
Eli Friedman59b66882011-08-09 23:02:53 +00004216 InstructionList.push_back(I);
4217 break;
4218 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004219 case bitc::FUNC_CODE_INST_STORE:
4220 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004221 unsigned OpNum = 0;
4222 Value *Val, *Ptr;
4223 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004224 (BitCode == bitc::FUNC_CODE_INST_STORE
4225 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4226 : popValue(Record, OpNum, NextValueNo,
4227 cast<PointerType>(Ptr->getType())->getElementType(),
4228 Val)) ||
4229 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004230 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004231
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004232 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4233 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004234 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004235 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4236 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004237 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004238 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004239 break;
4240 }
David Blaikie50a06152015-04-22 04:14:46 +00004241 case bitc::FUNC_CODE_INST_STOREATOMIC:
4242 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004243 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4244 unsigned OpNum = 0;
4245 Value *Val, *Ptr;
4246 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00004247 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00004248 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4249 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4250 : popValue(Record, OpNum, NextValueNo,
4251 cast<PointerType>(Ptr->getType())->getElementType(),
4252 Val)) ||
4253 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004254 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004255
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004256 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4257 return Err;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004258 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004259 if (Ordering == AtomicOrdering::NotAtomic ||
4260 Ordering == AtomicOrdering::Acquire ||
4261 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004262 return error("Invalid record");
4263 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00004264 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004265 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004266
JF Bastien30bf96b2015-02-22 19:32:03 +00004267 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004268 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4269 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004270 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004271 InstructionList.push_back(I);
4272 break;
4273 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004274 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004275 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004276 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004277 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004278 unsigned OpNum = 0;
4279 Value *Ptr, *Cmp, *New;
4280 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004281 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4282 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4283 : popValue(Record, OpNum, NextValueNo,
4284 cast<PointerType>(Ptr->getType())->getElementType(),
4285 Cmp)) ||
4286 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4287 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004288 return error("Invalid record");
4289 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00004290 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4291 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004292 return error("Invalid record");
4293 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004294
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004295 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4296 return Err;
Tim Northovere94a5182014-03-11 10:48:52 +00004297 AtomicOrdering FailureOrdering;
4298 if (Record.size() < 7)
4299 FailureOrdering =
4300 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4301 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004302 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004303
4304 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4305 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004306 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004307
4308 if (Record.size() < 8) {
4309 // Before weak cmpxchgs existed, the instruction simply returned the
4310 // value loaded from memory, so bitcode files from that era will be
4311 // expecting the first component of a modern cmpxchg.
4312 CurBB->getInstList().push_back(I);
4313 I = ExtractValueInst::Create(I, 0);
4314 } else {
4315 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4316 }
4317
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004318 InstructionList.push_back(I);
4319 break;
4320 }
4321 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4322 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4323 unsigned OpNum = 0;
4324 Value *Ptr, *Val;
4325 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00004326 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004327 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004328 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4329 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004330 return error("Invalid record");
4331 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004332 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4333 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004334 return error("Invalid record");
4335 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004336 if (Ordering == AtomicOrdering::NotAtomic ||
4337 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004338 return error("Invalid record");
4339 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004340 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4341 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4342 InstructionList.push_back(I);
4343 break;
4344 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00004345 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4346 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004347 return error("Invalid record");
4348 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00004349 if (Ordering == AtomicOrdering::NotAtomic ||
4350 Ordering == AtomicOrdering::Unordered ||
4351 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004352 return error("Invalid record");
4353 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004354 I = new FenceInst(Context, Ordering, SynchScope);
4355 InstructionList.push_back(I);
4356 break;
4357 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004358 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004359 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004360 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004361 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004362
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004363 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004364 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004365 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004366
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004367 FastMathFlags FMF;
4368 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4369 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4370 if (!FMF.any())
4371 return error("Fast math flags indicator set for call with no FMF");
4372 }
4373
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004374 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004375 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004376 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004377 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004378
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004379 Value *Callee;
4380 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004381 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004382
Chris Lattner229907c2011-07-18 04:54:35 +00004383 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004384 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004385 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004386 if (!FTy) {
4387 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4388 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004389 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00004390 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004391 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004392 "callee operand");
4393 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004394 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004395
Chris Lattner9f600c52007-05-03 22:04:19 +00004396 SmallVector<Value*, 16> Args;
4397 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004398 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004399 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004400 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004401 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004402 Args.push_back(getValue(Record, OpNum, NextValueNo,
4403 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004404 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004405 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004406 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004407
Chris Lattner9f600c52007-05-03 22:04:19 +00004408 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004409 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004410 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004411 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004412 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004413 while (OpNum != Record.size()) {
4414 Value *Op;
4415 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004416 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004417 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004418 }
4419 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004420
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004421 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4422 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004423 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004424 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004425 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00004426 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004427 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00004428 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004429 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00004430 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004431 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004432 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00004433 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004434 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004435 if (FMF.any()) {
4436 if (!isa<FPMathOperator>(I))
4437 return error("Fast-math-flags specified for call without "
4438 "floating-point scalar or vector return type");
4439 I->setFastMathFlags(FMF);
4440 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004441 break;
4442 }
4443 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4444 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004445 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004446 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004447 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004448 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004449 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004450 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004451 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004452 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004453 break;
4454 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004455
4456 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4457 // A call or an invoke can be optionally prefixed with some variable
4458 // number of operand bundle blocks. These blocks are read into
4459 // OperandBundles and consumed at the next call or invoke instruction.
4460
4461 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4462 return error("Invalid record");
4463
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004464 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004465
4466 unsigned OpNum = 1;
4467 while (OpNum != Record.size()) {
4468 Value *Op;
4469 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4470 return error("Invalid record");
4471 Inputs.push_back(Op);
4472 }
4473
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004474 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004475 continue;
4476 }
Chris Lattner83930552007-05-01 07:01:57 +00004477 }
4478
4479 // Add instruction to end of current BB. If there is no current BB, reject
4480 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004481 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00004482 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004483 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004484 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004485 if (!OperandBundles.empty()) {
4486 delete I;
4487 return error("Operand bundles found with no consumer");
4488 }
Chris Lattner83930552007-05-01 07:01:57 +00004489 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004490
Chris Lattner83930552007-05-01 07:01:57 +00004491 // If this was a terminator instruction, move to the next block.
4492 if (isa<TerminatorInst>(I)) {
4493 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004494 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004495 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004496
Chris Lattner83930552007-05-01 07:01:57 +00004497 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004498 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00004499 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004500 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004501
Chris Lattner27d38752013-01-20 02:13:19 +00004502OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004503
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004504 if (!OperandBundles.empty())
4505 return error("Operand bundles found with no consumer");
4506
Chris Lattner83930552007-05-01 07:01:57 +00004507 // Check the function list for unresolved values.
4508 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004509 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004510 // We found at least one unresolved value. Nuke them all to avoid leaks.
4511 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004512 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004513 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004514 delete A;
4515 }
4516 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004517 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004518 }
Chris Lattner83930552007-05-01 07:01:57 +00004519 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004520
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004521 // Unexpected unresolved metadata about to be dropped.
Mehdi Aminief27db82016-12-12 19:34:26 +00004522 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004523 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00004524
Chris Lattner85b7b402007-05-01 05:52:21 +00004525 // Trim the value list down to the size it was before we parsed this function.
4526 ValueList.shrinkTo(ModuleValueListSize);
Mehdi Aminief27db82016-12-12 19:34:26 +00004527 MDLoader->shrinkTo(ModuleMDLoaderSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004528 std::vector<BasicBlock*>().swap(FunctionBBs);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004529 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004530}
4531
Rafael Espindola7d712032013-11-05 17:16:08 +00004532/// Find the function body in the bitcode stream
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004533Error BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004534 Function *F,
4535 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004536 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00004537 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00004538 // didn't contain the function index in the VST, or when we have
4539 // an anonymous function which would not have a VST entry.
4540 // Assert that we have one of those two cases.
4541 assert(VSTOffset == 0 || !F->hasName());
4542 // Parse the next body in the stream and set its position in the
4543 // DeferredFunctionInfo map.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004544 if (Error Err = rememberAndSkipFunctionBodies())
4545 return Err;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004546 }
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004547 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004548}
4549
Chris Lattner9eeada92007-05-18 04:02:46 +00004550//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004551// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004552//===----------------------------------------------------------------------===//
4553
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004554Error BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004555 Function *F = dyn_cast<Function>(GV);
4556 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004557 if (!F || !F->isMaterializable())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004558 return Error::success();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004559
4560 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004561 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004562 // If its position is recorded as 0, its body is somewhere in the stream
4563 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004564 if (DFII->second == 0)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004565 if (Error Err = findFunctionInStream(F, DFII))
4566 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004567
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004568 // Materialize metadata before parsing any function bodies.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004569 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004570 return Err;
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004571
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004572 // Move the bit stream to the saved position of the deferred function body.
4573 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004574
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004575 if (Error Err = parseFunctionBody(F))
4576 return Err;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004577 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004578
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004579 if (StripDebugInfo)
4580 stripDebugInfo(*F);
4581
Chandler Carruth7132e002007-08-04 01:51:18 +00004582 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004583 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00004584 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4585 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004586 User *U = *UI;
4587 ++UI;
4588 if (CallInst *CI = dyn_cast<CallInst>(U))
4589 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004590 }
4591 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004592
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004593 // Update calls to the remangled intrinsics
4594 for (auto &I : RemangledIntrinsics)
4595 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4596 UI != UE;)
4597 // Don't expect any other users than call sites
4598 CallSite(*UI++).setCalledFunction(I.second);
4599
Peter Collingbourned4bff302015-11-05 22:03:56 +00004600 // Finish fn->subprogram upgrade for materialized functions.
Mehdi Aminief27db82016-12-12 19:34:26 +00004601 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
Peter Collingbourned4bff302015-11-05 22:03:56 +00004602 F->setSubprogram(SP);
4603
Mehdi Amini86623052016-12-16 19:16:29 +00004604 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4605 if (!MDLoader->isStrippingTBAA()) {
4606 for (auto &I : instructions(F)) {
4607 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4608 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4609 continue;
4610 MDLoader->setStripTBAA(true);
4611 stripTBAA(F->getParent());
4612 }
4613 }
4614
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004615 // Bring in any functions that this function forward-referenced via
4616 // blockaddresses.
4617 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004618}
4619
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004620Error BitcodeReader::materializeModule() {
4621 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004622 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004623
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004624 // Promise to materialize all forward references.
4625 WillMaterializeAllForwardRefs = true;
4626
Chris Lattner06310bf2009-06-16 05:15:21 +00004627 // Iterate over the module, deserializing any functions that are still on
4628 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004629 for (Function &F : *TheModule) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004630 if (Error Err = materialize(&F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004631 return Err;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004632 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00004633 // At this point, if there are any function bodies, parse the rest of
4634 // the bits in the module past the last function block we have recorded
4635 // through either lazy scanning or the VST.
4636 if (LastFunctionBlockBit || NextUnreadBit)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004637 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4638 ? LastFunctionBlockBit
4639 : NextUnreadBit))
4640 return Err;
Derek Schuff92ef9752012-02-29 00:07:09 +00004641
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004642 // Check that all block address forward references got resolved (as we
4643 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004644 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004645 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004646
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004647 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4648 // delete the old functions to clean up. We can't do this unless the entire
4649 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004650 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004651 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004652 for (auto *U : I.first->users()) {
4653 if (CallInst *CI = dyn_cast<CallInst>(U))
4654 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004655 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004656 if (!I.first->use_empty())
4657 I.first->replaceAllUsesWith(I.second);
4658 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004659 }
Rafael Espindola4e721212015-07-02 16:22:40 +00004660 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004661 // Do the same for remangled intrinsics
4662 for (auto &I : RemangledIntrinsics) {
4663 I.first->replaceAllUsesWith(I.second);
4664 I.first->eraseFromParent();
4665 }
4666 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00004667
Rafael Espindola79753a02015-12-18 21:18:57 +00004668 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00004669
4670 UpgradeModuleFlags(*TheModule);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004671 return Error::success();
Chris Lattner9eeada92007-05-18 04:02:46 +00004672}
4673
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004674std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4675 return IdentifiedStructTypes;
4676}
4677
Teresa Johnson26ab5772016-03-15 00:04:37 +00004678ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004679 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex)
4680 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00004681
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004682std::pair<GlobalValue::GUID, GlobalValue::GUID>
Mehdi Aminiad5741b2016-04-02 05:07:53 +00004683ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004684 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
4685 assert(VGI != ValueIdToCallGraphGUIDMap.end());
4686 return VGI->second;
4687}
4688
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004689void ModuleSummaryIndexBitcodeReader::setValueGUID(
4690 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4691 StringRef SourceFileName) {
4692 std::string GlobalId =
4693 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4694 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4695 auto OriginalNameID = ValueGUID;
4696 if (GlobalValue::isLocalLinkage(Linkage))
4697 OriginalNameID = GlobalValue::getGUID(ValueName);
4698 if (PrintSummaryGUIDs)
4699 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4700 << ValueName << "\n";
4701 ValueIdToCallGraphGUIDMap[ValueID] =
4702 std::make_pair(ValueGUID, OriginalNameID);
4703}
4704
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004705// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00004706// blocks where we don't actually create global values. The parsed information
4707// is saved in the bitcode reader for use when later parsing summaries.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004708Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004709 uint64_t Offset,
4710 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004711 // With a strtab the VST is not required to parse the summary.
4712 if (UseStrtab)
4713 return Error::success();
4714
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004715 assert(Offset > 0 && "Expected non-zero VST offset");
4716 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4717
Teresa Johnson403a7872015-10-04 14:33:43 +00004718 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4719 return error("Invalid record");
4720
4721 SmallVector<uint64_t, 64> Record;
4722
4723 // Read all the records for this value table.
4724 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004725
4726 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4728
4729 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004730 case BitstreamEntry::SubBlock: // Handled for us already.
4731 case BitstreamEntry::Error:
4732 return error("Malformed block");
4733 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004734 // Done parsing VST, jump back to wherever we came from.
4735 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004736 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004737 case BitstreamEntry::Record:
4738 // The interesting case.
4739 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00004740 }
4741
4742 // Read a record.
4743 Record.clear();
4744 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004745 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4746 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004747 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4748 if (convertToString(Record, 1, ValueName))
4749 return error("Invalid record");
4750 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004751 assert(!SourceFileName.empty());
4752 auto VLI = ValueIdToLinkageMap.find(ValueID);
4753 assert(VLI != ValueIdToLinkageMap.end() &&
4754 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004755 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004756 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004757 ValueName.clear();
4758 break;
4759 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004760 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00004761 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004762 if (convertToString(Record, 2, ValueName))
4763 return error("Invalid record");
4764 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004765 assert(!SourceFileName.empty());
4766 auto VLI = ValueIdToLinkageMap.find(ValueID);
4767 assert(VLI != ValueIdToLinkageMap.end() &&
4768 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004769 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004770 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004771 ValueName.clear();
4772 break;
4773 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004774 case bitc::VST_CODE_COMBINED_ENTRY: {
4775 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4776 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00004777 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004778 // The "original name", which is the second value of the pair will be
4779 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
4780 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004781 break;
4782 }
Teresa Johnson403a7872015-10-04 14:33:43 +00004783 }
4784 }
4785}
4786
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004787// Parse just the blocks needed for building the index out of the module.
4788// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00004789// from global value id to GlobalValueSummary objects.
Peter Collingbournec0032b72016-11-11 19:50:10 +00004790Error ModuleSummaryIndexBitcodeReader::parseModule(StringRef ModulePath) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004791 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4792 return error("Invalid record");
4793
Teresa Johnsone1164de2016-02-10 21:55:02 +00004794 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004795 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4796 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004797
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004798 // Read the index for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004799 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004800 BitstreamEntry Entry = Stream.advance();
4801
4802 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004803 case BitstreamEntry::Error:
4804 return error("Malformed block");
4805 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004806 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004807
4808 case BitstreamEntry::SubBlock:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004809 switch (Entry.ID) {
4810 default: // Skip unknown content.
4811 if (Stream.SkipBlock())
4812 return error("Invalid record");
4813 break;
4814 case bitc::BLOCKINFO_BLOCK_ID:
4815 // Need to parse these to get abbrev ids (e.g. for VST)
Peter Collingbourne939c7d92016-11-08 04:16:57 +00004816 if (readBlockInfo())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004817 return error("Malformed block");
4818 break;
4819 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004820 // Should have been parsed earlier via VSTOffset, unless there
4821 // is no summary section.
4822 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4823 !SeenGlobalValSummary) &&
4824 "Expected early VST parse via VSTOffset record");
4825 if (Stream.SkipBlock())
4826 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004827 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004828 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004829 assert(!SeenValueSymbolTable &&
4830 "Already read VST when parsing summary block?");
Teresa Johnson620c1402016-09-20 23:07:17 +00004831 // We might not have a VST if there were no values in the
4832 // summary. An empty summary block generated when we are
4833 // performing ThinLTO compiles so we don't later invoke
4834 // the regular LTO process on them.
4835 if (VSTOffset > 0) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004836 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4837 return Err;
Teresa Johnson620c1402016-09-20 23:07:17 +00004838 SeenValueSymbolTable = true;
4839 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004840 SeenGlobalValSummary = true;
Peter Collingbournec0032b72016-11-11 19:50:10 +00004841 if (Error Err = parseEntireSummary(ModulePath))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004842 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004843 break;
4844 case bitc::MODULE_STRTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004845 if (Error Err = parseModuleStringTable())
4846 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004847 break;
4848 }
4849 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00004850
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004851 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004852 Record.clear();
4853 auto BitCode = Stream.readRecord(Entry.ID, Record);
4854 switch (BitCode) {
4855 default:
4856 break; // Default behavior, ignore unknown content.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004857 case bitc::MODULE_CODE_VERSION: {
4858 if (Error Err = parseVersionRecord(Record).takeError())
4859 return Err;
4860 break;
4861 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00004862 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004863 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004864 SmallString<128> ValueName;
4865 if (convertToString(Record, 0, ValueName))
4866 return error("Invalid record");
4867 SourceFileName = ValueName.c_str();
4868 break;
4869 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004870 /// MODULE_CODE_HASH: [5*i32]
4871 case bitc::MODULE_CODE_HASH: {
4872 if (Record.size() != 5)
4873 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00004874 if (TheIndex.modulePaths().empty())
Mehdi Amini00fa1402016-10-08 04:44:18 +00004875 // We always seed the index with the module.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00004876 TheIndex.addModulePath(ModulePath, 0);
4877 if (TheIndex.modulePaths().size() != 1)
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004878 return error("Don't expect multiple modules defined?");
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00004879 auto &Hash = TheIndex.modulePaths().begin()->second.second;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004880 int Pos = 0;
4881 for (auto &Val : Record) {
4882 assert(!(Val >> 32) && "Unexpected high bits set");
4883 Hash[Pos++] = Val;
4884 }
4885 break;
4886 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004887 /// MODULE_CODE_VSTOFFSET: [offset]
4888 case bitc::MODULE_CODE_VSTOFFSET:
4889 if (Record.size() < 1)
4890 return error("Invalid record");
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00004891 // Note that we subtract 1 here because the offset is relative to one
4892 // word before the start of the identification or module block, which
4893 // was historically always the start of the regular bitcode header.
4894 VSTOffset = Record[0] - 1;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004895 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004896 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
4897 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
4898 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
4899 // v2: [strtab offset, strtab size, v1]
Peter Collingbournef43e0ae2017-04-10 21:17:54 +00004900 case bitc::MODULE_CODE_GLOBALVAR:
4901 case bitc::MODULE_CODE_FUNCTION:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004902 case bitc::MODULE_CODE_ALIAS: {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004903 StringRef Name;
4904 ArrayRef<uint64_t> GVRecord;
4905 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
4906 if (GVRecord.size() <= 3)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004907 return error("Invalid record");
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004908 uint64_t RawLinkage = GVRecord[3];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004909 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004910 if (!UseStrtab) {
4911 ValueIdToLinkageMap[ValueId++] = Linkage;
4912 break;
4913 }
4914
4915 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004916 break;
4917 }
4918 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00004919 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004920 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00004921 }
4922 }
4923}
4924
Peter Collingbourne0c30f082016-12-20 21:12:28 +00004925std::vector<ValueInfo>
4926ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
4927 std::vector<ValueInfo> Ret;
4928 Ret.reserve(Record.size());
4929 for (uint64_t RefValueId : Record)
4930 Ret.push_back(getGUIDFromValueId(RefValueId).first);
4931 return Ret;
4932}
4933
4934std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
4935 ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
4936 std::vector<FunctionSummary::EdgeTy> Ret;
4937 Ret.reserve(Record.size());
4938 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
4939 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
4940 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(Record[I]).first;
4941 if (IsOldProfileFormat) {
4942 I += 1; // Skip old callsitecount field
4943 if (HasProfile)
4944 I += 1; // Skip old profilecount field
4945 } else if (HasProfile)
4946 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
4947 Ret.push_back(FunctionSummary::EdgeTy{CalleeGUID, CalleeInfo{Hotness}});
4948 }
4949 return Ret;
4950}
4951
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004952// Eagerly parse the entire summary block. This populates the GlobalValueSummary
4953// objects in the index.
Peter Collingbournec0032b72016-11-11 19:50:10 +00004954Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
4955 StringRef ModulePath) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004956 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00004957 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00004958 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00004959
4960 // Parse version
4961 {
4962 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4963 if (Entry.Kind != BitstreamEntry::Record)
4964 return error("Invalid Summary Block: record for version expected");
4965 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
4966 return error("Invalid Summary Block: version expected");
4967 }
4968 const uint64_t Version = Record[0];
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00004969 const bool IsOldProfileFormat = Version == 1;
Teresa Johnson519465b2017-01-05 14:32:16 +00004970 if (Version < 1 || Version > 3)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00004971 return error("Invalid summary version " + Twine(Version) +
Teresa Johnson519465b2017-01-05 14:32:16 +00004972 ", 1, 2 or 3 expected");
Mehdi Amini8fe69362016-04-24 03:18:11 +00004973 Record.clear();
4974
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004975 // Keep around the last seen summary to be used when we see an optional
4976 // "OriginalName" attachement.
4977 GlobalValueSummary *LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00004978 GlobalValue::GUID LastSeenGUID = 0;
Peter Collingbournefa3175f2017-02-11 03:19:22 +00004979
4980 // We can expect to see any number of type ID information records before
4981 // each function summary records; these variables store the information
4982 // collected so far so that it can be used to create the summary object.
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00004983 std::vector<GlobalValue::GUID> PendingTypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00004984 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
4985 PendingTypeCheckedLoadVCalls;
4986 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
4987 PendingTypeCheckedLoadConstVCalls;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004988
4989 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004990 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4991
4992 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004993 case BitstreamEntry::SubBlock: // Handled for us already.
4994 case BitstreamEntry::Error:
4995 return error("Malformed block");
4996 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004997 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004998 case BitstreamEntry::Record:
4999 // The interesting case.
5000 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005001 }
5002
5003 // Read a record. The record format depends on whether this
5004 // is a per-module index or a combined index file. In the per-module
5005 // case the records contain the associated value's ID for correlation
5006 // with VST entries. In the combined index the correlation is done
5007 // via the bitcode offset of the summary records (which were saved
5008 // in the combined index VST entries). The records also contain
5009 // information used for ThinLTO renaming and importing.
5010 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005011 auto BitCode = Stream.readRecord(Entry.ID, Record);
5012 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005013 default: // Default behavior: ignore.
5014 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005015 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5016 uint64_t ValueID = Record[0];
5017 GlobalValue::GUID RefGUID = Record[1];
5018 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
5019 break;
5020 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005021 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005022 // n x (valueid)]
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005023 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005024 // numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005025 // n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005026 case bitc::FS_PERMODULE:
5027 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005028 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005029 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005030 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005031 unsigned NumRefs = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005032 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005033 // The module path string ref set in the summary must be owned by the
5034 // index's module string table. Since we don't have a module path
5035 // string table section in the per-module index, we create a single
5036 // module path string table entry with an empty (0) ID to take
5037 // ownership.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005038 static int RefListStartIndex = 4;
5039 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5040 assert(Record.size() >= RefListStartIndex + NumRefs &&
5041 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005042 std::vector<ValueInfo> Refs = makeRefList(
5043 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005044 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005045 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5046 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5047 IsOldProfileFormat, HasProfile);
5048 auto FS = llvm::make_unique<FunctionSummary>(
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005049 Flags, InstCount, std::move(Refs), std::move(Calls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005050 std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5051 std::move(PendingTypeCheckedLoadVCalls),
5052 std::move(PendingTypeTestAssumeConstVCalls),
5053 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005054 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005055 PendingTypeTestAssumeVCalls.clear();
5056 PendingTypeCheckedLoadVCalls.clear();
5057 PendingTypeTestAssumeConstVCalls.clear();
5058 PendingTypeCheckedLoadConstVCalls.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005059 auto GUID = getGUIDFromValueId(ValueID);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005060 FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005061 FS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005062 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005063 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005064 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005065 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005066 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5067 // they expect all aliasee summaries to be available.
5068 case bitc::FS_ALIAS: {
5069 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005070 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005071 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005072 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005073 auto AS =
5074 llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005075 // The module path string ref set in the summary must be owned by the
5076 // index's module string table. Since we don't have a module path
5077 // string table section in the per-module index, we create a single
5078 // module path string table entry with an empty (0) ID to take
5079 // ownership.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005080 AS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005081
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005082 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005083 auto *AliaseeSummary = TheIndex.getGlobalValueSummary(AliaseeGUID);
Teresa Johnson28e457b2016-04-24 14:57:11 +00005084 if (!AliaseeSummary)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005085 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson28e457b2016-04-24 14:57:11 +00005086 AS->setAliasee(AliaseeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005087
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005088 auto GUID = getGUIDFromValueId(ValueID);
5089 AS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005090 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005091 break;
5092 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005093 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005094 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5095 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005096 uint64_t RawFlags = Record[1];
5097 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005098 std::vector<ValueInfo> Refs =
5099 makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5100 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005101 FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005102 auto GUID = getGUIDFromValueId(ValueID);
5103 FS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005104 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005105 break;
5106 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005107 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005108 // numrefs x valueid, n x (valueid)]
Teresa Johnson02e98332016-04-27 13:28:35 +00005109 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005110 // numrefs x valueid, n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005111 case bitc::FS_COMBINED:
5112 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005113 unsigned ValueID = Record[0];
5114 uint64_t ModuleId = Record[1];
5115 uint64_t RawFlags = Record[2];
5116 unsigned InstCount = Record[3];
5117 unsigned NumRefs = Record[4];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005118 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson02e98332016-04-27 13:28:35 +00005119 static int RefListStartIndex = 5;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005120 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5121 assert(Record.size() >= RefListStartIndex + NumRefs &&
5122 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005123 std::vector<ValueInfo> Refs = makeRefList(
5124 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005125 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005126 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5127 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5128 IsOldProfileFormat, HasProfile);
Teresa Johnson02e98332016-04-27 13:28:35 +00005129 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005130 auto FS = llvm::make_unique<FunctionSummary>(
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005131 Flags, InstCount, std::move(Refs), std::move(Edges),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005132 std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5133 std::move(PendingTypeCheckedLoadVCalls),
5134 std::move(PendingTypeTestAssumeConstVCalls),
5135 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005136 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005137 PendingTypeTestAssumeVCalls.clear();
5138 PendingTypeCheckedLoadVCalls.clear();
5139 PendingTypeTestAssumeConstVCalls.clear();
5140 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005141 LastSeenSummary = FS.get();
Dehao Chen4a435e02017-03-14 17:33:01 +00005142 LastSeenGUID = GUID;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005143 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005144 TheIndex.addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005145 break;
5146 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005147 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005148 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5149 // they expect all aliasee summaries to be available.
5150 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005151 unsigned ValueID = Record[0];
5152 uint64_t ModuleId = Record[1];
5153 uint64_t RawFlags = Record[2];
5154 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005155 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005156 auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005157 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005158 AS->setModulePath(ModuleIdMap[ModuleId]);
5159
Teresa Johnson02e98332016-04-27 13:28:35 +00005160 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
5161 auto AliaseeInModule =
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005162 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
Teresa Johnson02e98332016-04-27 13:28:35 +00005163 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005164 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00005165 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005166
Teresa Johnson02e98332016-04-27 13:28:35 +00005167 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Dehao Chen4a435e02017-03-14 17:33:01 +00005168 LastSeenGUID = GUID;
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005169 TheIndex.addGlobalValueSummary(GUID, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005170 break;
5171 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005172 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005173 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005174 unsigned ValueID = Record[0];
5175 uint64_t ModuleId = Record[1];
5176 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005177 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005178 std::vector<ValueInfo> Refs =
5179 makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5180 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005181 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005182 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00005183 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Dehao Chen4a435e02017-03-14 17:33:01 +00005184 LastSeenGUID = GUID;
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005185 TheIndex.addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005186 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005187 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005188 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5189 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5190 uint64_t OriginalName = Record[0];
5191 if (!LastSeenSummary)
5192 return error("Name attachment that does not follow a combined record");
5193 LastSeenSummary->setOriginalName(OriginalName);
Dehao Chen4a435e02017-03-14 17:33:01 +00005194 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005195 // Reset the LastSeenSummary
5196 LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005197 LastSeenGUID = 0;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005198 break;
5199 }
5200 case bitc::FS_TYPE_TESTS: {
5201 assert(PendingTypeTests.empty());
5202 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5203 Record.end());
5204 break;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005205 }
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005206 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: {
5207 assert(PendingTypeTestAssumeVCalls.empty());
5208 for (unsigned I = 0; I != Record.size(); I += 2)
5209 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5210 break;
5211 }
5212 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: {
5213 assert(PendingTypeCheckedLoadVCalls.empty());
5214 for (unsigned I = 0; I != Record.size(); I += 2)
5215 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5216 break;
5217 }
5218 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: {
5219 PendingTypeTestAssumeConstVCalls.push_back(
5220 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5221 break;
5222 }
5223 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: {
5224 PendingTypeCheckedLoadConstVCalls.push_back(
5225 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5226 break;
5227 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005228 }
5229 }
5230 llvm_unreachable("Exit infinite loop");
5231}
5232
5233// Parse the module string table block into the Index.
5234// This populates the ModulePathStringTable map in the index.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005235Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005236 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5237 return error("Invalid record");
5238
5239 SmallVector<uint64_t, 64> Record;
5240
5241 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005242 ModulePathStringTableTy::iterator LastSeenModulePath;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005243
5244 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005245 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5246
5247 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005248 case BitstreamEntry::SubBlock: // Handled for us already.
5249 case BitstreamEntry::Error:
5250 return error("Malformed block");
5251 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005252 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005253 case BitstreamEntry::Record:
5254 // The interesting case.
5255 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005256 }
5257
5258 Record.clear();
5259 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005260 default: // Default behavior: ignore.
5261 break;
5262 case bitc::MST_CODE_ENTRY: {
5263 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005264 uint64_t ModuleId = Record[0];
5265
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005266 if (convertToString(Record, 1, ModulePath))
5267 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005268
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005269 LastSeenModulePath = TheIndex.addModulePath(ModulePath, ModuleId);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005270 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5271
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005272 ModulePath.clear();
5273 break;
5274 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005275 /// MST_CODE_HASH: [5*i32]
5276 case bitc::MST_CODE_HASH: {
5277 if (Record.size() != 5)
5278 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005279 if (LastSeenModulePath == TheIndex.modulePaths().end())
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005280 return error("Invalid hash that does not follow a module path");
5281 int Pos = 0;
5282 for (auto &Val : Record) {
5283 assert(!(Val >> 32) && "Unexpected high bits set");
5284 LastSeenModulePath->second.second[Pos++] = Val;
5285 }
5286 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005287 LastSeenModulePath = TheIndex.modulePaths().end();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005288 break;
5289 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005290 }
5291 }
5292 llvm_unreachable("Exit infinite loop");
5293}
5294
Rafael Espindola48da4f42013-11-04 16:16:24 +00005295namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +00005296
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00005297// FIXME: This class is only here to support the transition to llvm::Error. It
5298// will be removed once this transition is complete. Clients should prefer to
5299// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00005300class BitcodeErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +00005301 const char *name() const noexcept override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00005302 return "llvm.bitcode";
5303 }
Craig Topper73156022014-03-02 09:09:27 +00005304 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005305 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005306 switch (E) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005307 case BitcodeError::CorruptedBitcode:
5308 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00005309 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00005310 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00005311 }
5312};
Eugene Zelenko1804a772016-08-25 00:45:04 +00005313
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00005314} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00005315
Chris Bieneman770163e2014-09-19 20:29:02 +00005316static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5317
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005318const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00005319 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005320}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005321
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005322static Expected<StringRef> readStrtab(BitstreamCursor &Stream) {
5323 if (Stream.EnterSubBlock(bitc::STRTAB_BLOCK_ID))
5324 return error("Invalid record");
5325
5326 StringRef Strtab;
5327 while (1) {
5328 BitstreamEntry Entry = Stream.advance();
5329 switch (Entry.Kind) {
5330 case BitstreamEntry::EndBlock:
5331 return Strtab;
5332
5333 case BitstreamEntry::Error:
5334 return error("Malformed block");
5335
5336 case BitstreamEntry::SubBlock:
5337 if (Stream.SkipBlock())
5338 return error("Malformed block");
5339 break;
5340
5341 case BitstreamEntry::Record:
5342 StringRef Blob;
5343 SmallVector<uint64_t, 1> Record;
5344 if (Stream.readRecord(Entry.ID, Record, &Blob) == bitc::STRTAB_BLOB)
5345 Strtab = Blob;
5346 break;
5347 }
5348 }
5349}
5350
Chris Lattner6694f602007-04-29 07:54:31 +00005351//===----------------------------------------------------------------------===//
5352// External interface
5353//===----------------------------------------------------------------------===//
5354
Peter Collingbourne7a748032016-11-16 21:44:45 +00005355Expected<std::vector<BitcodeModule>>
5356llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5357 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5358 if (!StreamOrErr)
5359 return StreamOrErr.takeError();
5360 BitstreamCursor &Stream = *StreamOrErr;
5361
Peter Collingbourne7a748032016-11-16 21:44:45 +00005362 std::vector<BitcodeModule> Modules;
5363 while (true) {
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005364 uint64_t BCBegin = Stream.getCurrentByteNo();
5365
Peter Collingbourne7a748032016-11-16 21:44:45 +00005366 // We may be consuming bitcode from a client that leaves garbage at the end
5367 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5368 // the end that there cannot possibly be another module, stop looking.
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005369 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
Peter Collingbourne7a748032016-11-16 21:44:45 +00005370 return Modules;
5371
5372 BitstreamEntry Entry = Stream.advance();
5373 switch (Entry.Kind) {
5374 case BitstreamEntry::EndBlock:
5375 case BitstreamEntry::Error:
5376 return error("Malformed block");
5377
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005378 case BitstreamEntry::SubBlock: {
5379 uint64_t IdentificationBit = -1ull;
5380 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5381 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5382 if (Stream.SkipBlock())
5383 return error("Malformed block");
5384
5385 Entry = Stream.advance();
5386 if (Entry.Kind != BitstreamEntry::SubBlock ||
5387 Entry.ID != bitc::MODULE_BLOCK_ID)
5388 return error("Malformed block");
5389 }
5390
5391 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5392 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5393 if (Stream.SkipBlock())
5394 return error("Malformed block");
5395
5396 Modules.push_back({Stream.getBitcodeBytes().slice(
5397 BCBegin, Stream.getCurrentByteNo() - BCBegin),
Peter Collingbourne7a748032016-11-16 21:44:45 +00005398 Buffer.getBufferIdentifier(), IdentificationBit,
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005399 ModuleBit});
5400 continue;
5401 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005402
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005403 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
5404 Expected<StringRef> Strtab = readStrtab(Stream);
5405 if (!Strtab)
5406 return Strtab.takeError();
5407 // This string table is used by every preceding bitcode module that does
5408 // not have its own string table. A bitcode file may have multiple
5409 // string tables if it was created by binary concatenation, for example
5410 // with "llvm-cat -b".
5411 for (auto I = Modules.rbegin(), E = Modules.rend(); I != E; ++I) {
5412 if (!I->Strtab.empty())
5413 break;
5414 I->Strtab = *Strtab;
5415 }
5416 continue;
5417 }
5418
Peter Collingbourne7a748032016-11-16 21:44:45 +00005419 if (Stream.SkipBlock())
5420 return error("Malformed block");
5421 continue;
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005422 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005423 case BitstreamEntry::Record:
5424 Stream.skipRecord(Entry.ID);
5425 continue;
5426 }
5427 }
5428}
5429
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005430/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00005431///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005432/// This isn't always used in a lazy context. In particular, it's also used by
Peter Collingbourne7a748032016-11-16 21:44:45 +00005433/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005434/// in forward-referenced functions from block address references.
5435///
Rafael Espindola728074b2015-06-17 00:40:56 +00005436/// \param[in] MaterializeAll Set to \c true if we should materialize
5437/// everything.
Peter Collingbourne7a748032016-11-16 21:44:45 +00005438Expected<std::unique_ptr<Module>>
5439BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005440 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005441 BitstreamCursor Stream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005442
Peter Collingbourne7a748032016-11-16 21:44:45 +00005443 std::string ProducerIdentification;
5444 if (IdentificationBit != -1ull) {
5445 Stream.JumpToBit(IdentificationBit);
5446 Expected<std::string> ProducerIdentificationOrErr =
5447 readIdentificationBlock(Stream);
5448 if (!ProducerIdentificationOrErr)
5449 return ProducerIdentificationOrErr.takeError();
5450
5451 ProducerIdentification = *ProducerIdentificationOrErr;
5452 }
5453
5454 Stream.JumpToBit(ModuleBit);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005455 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5456 Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005457
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005458 std::unique_ptr<Module> M =
Peter Collingbourne7a748032016-11-16 21:44:45 +00005459 llvm::make_unique<Module>(ModuleIdentifier, Context);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005460 M->setMaterializer(R);
Rafael Espindolab7993462012-01-02 07:49:53 +00005461
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005462 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005463 if (Error Err =
5464 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
Peter Collingbourned9445c42016-11-13 07:00:17 +00005465 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005466
5467 if (MaterializeAll) {
5468 // Read in the entire module, and destroy the BitcodeReader.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00005469 if (Error Err = M->materializeAll())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005470 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005471 } else {
5472 // Resolve forward references from blockaddresses.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005473 if (Error Err = R->materializeForwardReferencedFunctions())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005474 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005475 }
5476 return std::move(M);
Chris Lattner6694f602007-04-29 07:54:31 +00005477}
5478
Peter Collingbourned9445c42016-11-13 07:00:17 +00005479Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005480BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5481 bool IsImporting) {
5482 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005483}
5484
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005485// Parse the specified bitcode buffer, returning the function info index.
5486Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5487 BitstreamCursor Stream(Buffer);
5488 Stream.JumpToBit(ModuleBit);
5489
5490 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005491 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index);
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005492
5493 if (Error Err = R.parseModule(ModuleIdentifier))
5494 return std::move(Err);
5495
5496 return std::move(Index);
5497}
5498
5499// Check if the given bitcode buffer contains a global value summary block.
5500Expected<bool> BitcodeModule::hasSummary() {
5501 BitstreamCursor Stream(Buffer);
5502 Stream.JumpToBit(ModuleBit);
5503
5504 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5505 return error("Invalid record");
5506
5507 while (true) {
5508 BitstreamEntry Entry = Stream.advance();
5509
5510 switch (Entry.Kind) {
5511 case BitstreamEntry::Error:
5512 return error("Malformed block");
5513 case BitstreamEntry::EndBlock:
5514 return false;
5515
5516 case BitstreamEntry::SubBlock:
5517 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5518 return true;
5519
5520 // Ignore other sub-blocks.
5521 if (Stream.SkipBlock())
5522 return error("Malformed block");
5523 continue;
5524
5525 case BitstreamEntry::Record:
5526 Stream.skipRecord(Entry.ID);
5527 continue;
5528 }
5529 }
5530}
5531
5532static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005533 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5534 if (!MsOrErr)
5535 return MsOrErr.takeError();
5536
5537 if (MsOrErr->size() != 1)
5538 return error("Expected a single module");
5539
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005540 return (*MsOrErr)[0];
5541}
5542
5543Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005544llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5545 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005546 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5547 if (!BM)
5548 return BM.takeError();
5549
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005550 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005551}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005552
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005553Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5554 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5555 bool ShouldLazyLoadMetadata, bool IsImporting) {
5556 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5557 IsImporting);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005558 if (MOrErr)
5559 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5560 return MOrErr;
5561}
5562
Peter Collingbourne7a748032016-11-16 21:44:45 +00005563Expected<std::unique_ptr<Module>>
5564BitcodeModule::parseModule(LLVMContext &Context) {
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005565 return getModuleImpl(Context, true, false, false);
Chad Rosierca2567b2011-12-07 21:44:12 +00005566 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5567 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00005568}
Bill Wendling0198ce02010-10-06 01:22:42 +00005569
Peter Collingbourne7a748032016-11-16 21:44:45 +00005570Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5571 LLVMContext &Context) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005572 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5573 if (!BM)
5574 return BM.takeError();
Peter Collingbourne7a748032016-11-16 21:44:45 +00005575
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005576 return BM->parseModule(Context);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005577}
5578
Peter Collingbournecd513a42016-11-11 19:50:24 +00005579Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5580 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005581 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005582 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005583
Peter Collingbournecd513a42016-11-11 19:50:24 +00005584 return readTriple(*StreamOrErr);
Bill Wendling0198ce02010-10-06 01:22:42 +00005585}
Teresa Johnson403a7872015-10-04 14:33:43 +00005586
Peter Collingbournecd513a42016-11-11 19:50:24 +00005587Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5588 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005589 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005590 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005591
Peter Collingbournecd513a42016-11-11 19:50:24 +00005592 return hasObjCCategory(*StreamOrErr);
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00005593}
5594
Peter Collingbournecd513a42016-11-11 19:50:24 +00005595Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5596 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005597 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005598 return StreamOrErr.takeError();
5599
5600 return readIdentificationCode(*StreamOrErr);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00005601}
5602
Peter Collingbourne6de481a2016-11-11 19:50:39 +00005603Expected<std::unique_ptr<ModuleSummaryIndex>>
5604llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005605 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5606 if (!BM)
5607 return BM.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005608
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005609 return BM->getSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00005610}
5611
Peter Collingbournecd513a42016-11-11 19:50:24 +00005612Expected<bool> llvm::hasGlobalValueSummary(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005613 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5614 if (!BM)
5615 return BM.takeError();
Teresa Johnson403a7872015-10-04 14:33:43 +00005616
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005617 return BM->hasSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00005618}
Peter Collingbournec15d60b2017-05-01 20:42:32 +00005619
5620Expected<std::unique_ptr<ModuleSummaryIndex>>
5621llvm::getModuleSummaryIndexForFile(StringRef Path) {
5622 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5623 MemoryBuffer::getFileOrSTDIN(Path);
5624 if (!FileOrErr)
5625 return errorCodeToError(FileOrErr.getError());
5626 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5627 return nullptr;
5628 return getModuleSummaryIndex(**FileOrErr);
5629}