blob: 1ebef3173135363ff3f3fdc0670972d155f56df7 [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"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000031#include "llvm/IR/CallSite.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000032#include "llvm/IR/CallingConv.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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000043#include "llvm/IR/GVMaterializer.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalIFunc.h"
46#include "llvm/IR/GlobalIndirectSymbol.h"
47#include "llvm/IR/GlobalObject.h"
48#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/GlobalVariable.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
Benjamin Kramercced8be2015-03-17 20:40:24 +000096namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +000097
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000098enum {
99 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
100};
101
Peter Collingbournec0032b72016-11-11 19:50:10 +0000102Error error(const Twine &Message) {
103 return make_error<StringError>(
104 Message, make_error_code(BitcodeError::CorruptedBitcode));
105}
106
107/// Helper to read the header common to all bitcode files.
108bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
109 // Sniff for the signature.
110 if (!Stream.canSkipToPos(4) ||
111 Stream.Read(8) != 'B' ||
112 Stream.Read(8) != 'C' ||
113 Stream.Read(4) != 0x0 ||
114 Stream.Read(4) != 0xC ||
115 Stream.Read(4) != 0xE ||
116 Stream.Read(4) != 0xD)
117 return false;
118 return true;
119}
120
121Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
122 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
123 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
124
125 if (Buffer.getBufferSize() & 3)
126 return error("Invalid bitcode signature");
127
128 // If we have a wrapper header, parse it and ignore the non-bc file contents.
129 // The magic number is 0x0B17C0DE stored in little endian.
130 if (isBitcodeWrapper(BufPtr, BufEnd))
131 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
132 return error("Invalid bitcode wrapper header");
133
134 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
135 if (!hasValidBitcodeHeader(Stream))
136 return error("Invalid bitcode signature");
137
138 return std::move(Stream);
139}
140
Peter Collingbournecd513a42016-11-11 19:50:24 +0000141/// Convert a string from a record into an std::string, return true on failure.
142template <typename StrTy>
143static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
144 StrTy &Result) {
145 if (Idx > Record.size())
146 return true;
147
148 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
149 Result += (char)Record[i];
150 return false;
151}
152
Mehdi Amini86623052016-12-16 19:16:29 +0000153// Strip all the TBAA attachment for the module.
154void stripTBAA(Module *M) {
155 for (auto &F : *M) {
156 if (F.isMaterializable())
157 continue;
158 for (auto &I : instructions(F))
159 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
160 }
161}
162
Peter Collingbournecd513a42016-11-11 19:50:24 +0000163/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
164/// "epoch" encoded in the bitcode, and return the producer name if any.
165Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
166 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
167 return error("Invalid record");
168
169 // Read all the records.
170 SmallVector<uint64_t, 64> Record;
171
172 std::string ProducerIdentification;
173
174 while (true) {
175 BitstreamEntry Entry = Stream.advance();
176
177 switch (Entry.Kind) {
178 default:
179 case BitstreamEntry::Error:
180 return error("Malformed block");
181 case BitstreamEntry::EndBlock:
182 return ProducerIdentification;
183 case BitstreamEntry::Record:
184 // The interesting case.
185 break;
186 }
187
188 // Read a record.
189 Record.clear();
190 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
191 switch (BitCode) {
192 default: // Default behavior: reject
193 return error("Invalid value");
194 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
195 convertToString(Record, 0, ProducerIdentification);
196 break;
197 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
198 unsigned epoch = (unsigned)Record[0];
199 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
200 return error(
201 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
202 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
203 }
204 }
205 }
206 }
207}
208
209Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
210 // We expect a number of well-defined blocks, though we don't necessarily
211 // need to understand them all.
212 while (true) {
213 if (Stream.AtEndOfStream())
214 return "";
215
216 BitstreamEntry Entry = Stream.advance();
217 switch (Entry.Kind) {
218 case BitstreamEntry::EndBlock:
219 case BitstreamEntry::Error:
220 return error("Malformed block");
221
222 case BitstreamEntry::SubBlock:
223 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
224 return readIdentificationBlock(Stream);
225
226 // Ignore other sub-blocks.
227 if (Stream.SkipBlock())
228 return error("Malformed block");
229 continue;
230 case BitstreamEntry::Record:
231 Stream.skipRecord(Entry.ID);
232 continue;
233 }
234 }
235}
236
237Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
238 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
239 return error("Invalid record");
240
241 SmallVector<uint64_t, 64> Record;
242 // Read all the records for this module.
243
244 while (true) {
245 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
246
247 switch (Entry.Kind) {
248 case BitstreamEntry::SubBlock: // Handled for us already.
249 case BitstreamEntry::Error:
250 return error("Malformed block");
251 case BitstreamEntry::EndBlock:
252 return false;
253 case BitstreamEntry::Record:
254 // The interesting case.
255 break;
256 }
257
258 // Read a record.
259 switch (Stream.readRecord(Entry.ID, Record)) {
260 default:
261 break; // Default behavior, ignore unknown content.
262 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
263 std::string S;
264 if (convertToString(Record, 0, S))
265 return error("Invalid record");
266 // Check for the i386 and other (x86_64, ARM) conventions
267 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
268 S.find("__OBJC,__category") != std::string::npos)
269 return true;
270 break;
271 }
272 }
273 Record.clear();
274 }
275 llvm_unreachable("Exit infinite loop");
276}
277
278Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
279 // We expect a number of well-defined blocks, though we don't necessarily
280 // need to understand them all.
281 while (true) {
282 BitstreamEntry Entry = Stream.advance();
283
284 switch (Entry.Kind) {
285 case BitstreamEntry::Error:
286 return error("Malformed block");
287 case BitstreamEntry::EndBlock:
288 return false;
289
290 case BitstreamEntry::SubBlock:
291 if (Entry.ID == bitc::MODULE_BLOCK_ID)
292 return hasObjCCategoryInModule(Stream);
293
294 // Ignore other sub-blocks.
295 if (Stream.SkipBlock())
296 return error("Malformed block");
297 continue;
298
299 case BitstreamEntry::Record:
300 Stream.skipRecord(Entry.ID);
301 continue;
302 }
303 }
304}
305
306Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
307 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
308 return error("Invalid record");
309
310 SmallVector<uint64_t, 64> Record;
311
312 std::string Triple;
313
314 // Read all the records for this module.
315 while (true) {
316 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
317
318 switch (Entry.Kind) {
319 case BitstreamEntry::SubBlock: // Handled for us already.
320 case BitstreamEntry::Error:
321 return error("Malformed block");
322 case BitstreamEntry::EndBlock:
323 return Triple;
324 case BitstreamEntry::Record:
325 // The interesting case.
326 break;
327 }
328
329 // Read a record.
330 switch (Stream.readRecord(Entry.ID, Record)) {
331 default: break; // Default behavior, ignore unknown content.
332 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
333 std::string S;
334 if (convertToString(Record, 0, S))
335 return error("Invalid record");
336 Triple = S;
337 break;
338 }
339 }
340 Record.clear();
341 }
342 llvm_unreachable("Exit infinite loop");
343}
344
345Expected<std::string> readTriple(BitstreamCursor &Stream) {
346 // We expect a number of well-defined blocks, though we don't necessarily
347 // need to understand them all.
348 while (true) {
349 BitstreamEntry Entry = Stream.advance();
350
351 switch (Entry.Kind) {
352 case BitstreamEntry::Error:
353 return error("Malformed block");
354 case BitstreamEntry::EndBlock:
355 return "";
356
357 case BitstreamEntry::SubBlock:
358 if (Entry.ID == bitc::MODULE_BLOCK_ID)
359 return readModuleTriple(Stream);
360
361 // Ignore other sub-blocks.
362 if (Stream.SkipBlock())
363 return error("Malformed block");
364 continue;
365
366 case BitstreamEntry::Record:
367 Stream.skipRecord(Entry.ID);
368 continue;
369 }
370 }
371}
372
Peter Collingbourne6e860752016-09-23 18:27:42 +0000373class BitcodeReaderBase {
374protected:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000375 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
376 : Stream(std::move(Stream)), Strtab(Strtab) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000377 this->Stream.setBlockInfo(&BlockInfo);
378 }
Peter Collingbourne6e860752016-09-23 18:27:42 +0000379
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000380 BitstreamBlockInfo BlockInfo;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000381 BitstreamCursor Stream;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000382 StringRef Strtab;
383
384 /// In version 2 of the bitcode we store names of global values and comdats in
385 /// a string table rather than in the VST.
386 bool UseStrtab = false;
Peter Collingbourne6e860752016-09-23 18:27:42 +0000387
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000388 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
389
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000390 /// If this module uses a string table, pop the reference to the string table
391 /// and return the referenced string and the rest of the record. Otherwise
392 /// just return the record itself.
393 std::pair<StringRef, ArrayRef<uint64_t>>
394 readNameFromStrtab(ArrayRef<uint64_t> Record);
395
Peter Collingbourne939c7d92016-11-08 04:16:57 +0000396 bool readBlockInfo();
Peter Collingbourne6e860752016-09-23 18:27:42 +0000397
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000398 // Contains an arbitrary and optional string identifying the bitcode producer
399 std::string ProducerIdentification;
400
401 Error error(const Twine &Message);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000402};
403
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000404Error BitcodeReaderBase::error(const Twine &Message) {
405 std::string FullMsg = Message.str();
406 if (!ProducerIdentification.empty())
407 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
408 LLVM_VERSION_STRING "')";
Peter Collingbournec0032b72016-11-11 19:50:10 +0000409 return ::error(FullMsg);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000410}
411
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000412Expected<unsigned>
413BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
414 if (Record.size() < 1)
415 return error("Invalid record");
416 unsigned ModuleVersion = Record[0];
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000417 if (ModuleVersion > 2)
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000418 return error("Invalid value");
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000419 UseStrtab = ModuleVersion >= 2;
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000420 return ModuleVersion;
421}
422
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000423std::pair<StringRef, ArrayRef<uint64_t>>
424BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
425 if (!UseStrtab)
426 return {"", Record};
427 // Invalid reference. Let the caller complain about the record being empty.
428 if (Record[0] + Record[1] > Strtab.size())
429 return {"", {}};
430 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
431}
432
Peter Collingbourne6e860752016-09-23 18:27:42 +0000433class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
434 LLVMContext &Context;
435 Module *TheModule = nullptr;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000436 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000437 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000438 // Last function offset found in the VST.
439 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000440 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000441 uint64_t VSTOffset = 0;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000442
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000443 std::vector<std::string> SectionTable;
444 std::vector<std::string> GCTable;
445
Benjamin Kramercced8be2015-03-17 20:40:24 +0000446 std::vector<Type*> TypeList;
447 BitcodeReaderValueList ValueList;
Mehdi Aminief27db82016-12-12 19:34:26 +0000448 Optional<MetadataLoader> MDLoader;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000449 std::vector<Comdat *> ComdatList;
450 SmallVector<Instruction *, 64> InstructionList;
451
452 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000453 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000454 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
455 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000456 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000457
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000458 /// The set of attributes by index. Index zero in the file is for null, and
459 /// is thus not represented here. As such all indices are off by one.
Reid Klecknerb5180542017-03-21 16:57:19 +0000460 std::vector<AttributeList> MAttributes;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000461
Karl Schimpf36440082015-08-31 16:43:55 +0000462 /// The set of attribute groups.
Reid Klecknerb5180542017-03-21 16:57:19 +0000463 std::map<unsigned, AttributeList> MAttributeGroups;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000464
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000465 /// While parsing a function body, this is a list of the basic blocks for the
466 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000467 std::vector<BasicBlock*> FunctionBBs;
468
469 // When reading the module header, this list is populated with functions that
470 // have bodies later in the file.
471 std::vector<Function*> FunctionsWithBodies;
472
473 // When intrinsic functions are encountered which require upgrading they are
474 // stored here with their replacement function.
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000475 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
476 UpdatedIntrinsicMap UpgradedIntrinsics;
477 // Intrinsics which were remangled because of types rename
478 UpdatedIntrinsicMap RemangledIntrinsics;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000479
Benjamin Kramercced8be2015-03-17 20:40:24 +0000480 // Several operations happen after the module header has been read, but
481 // before function bodies are processed. This keeps track of whether
482 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000483 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000484
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000485 /// When function bodies are initially scanned, this map contains info about
486 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000487 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
488
489 /// When Metadata block is initially scanned when parsing the module, we may
490 /// choose to defer parsing of the metadata. This vector contains info about
491 /// which Metadata blocks are deferred.
492 std::vector<uint64_t> DeferredMetadataInfo;
493
494 /// These are basic blocks forward-referenced by block addresses. They are
495 /// inserted lazily into functions when they're loaded. The basic block ID is
496 /// its index into the vector.
497 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
498 std::deque<Function *> BasicBlockFwdRefQueue;
499
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000500 /// Indicates that we are using a new encoding for instruction operands where
501 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
502 /// instruction number, for a more compact encoding. Some instruction
503 /// operands are not relative to the instruction ID: basic block numbers, and
504 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000505 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000506 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000507
508 /// True if all functions will be materialized, negating the need to process
509 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000510 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000511
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000512 bool StripDebugInfo = false;
Mehdi Amini86623052016-12-16 19:16:29 +0000513 TBAAVerifier TBAAVerifyHelper;
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000514
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000515 std::vector<std::string> BundleTags;
516
Benjamin Kramercced8be2015-03-17 20:40:24 +0000517public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000518 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
519 StringRef ProducerIdentification, LLVMContext &Context);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000520
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000521 Error materializeForwardReferencedFunctions();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000522
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000523 Error materialize(GlobalValue *GV) override;
524 Error materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000525 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000526
Rafael Espindola6ace6852015-06-15 21:02:49 +0000527 /// \brief Main interface to parsing a bitcode buffer.
528 /// \returns true if an error occurred.
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000529 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
530 bool IsImporting = false);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000531
Benjamin Kramercced8be2015-03-17 20:40:24 +0000532 static uint64_t decodeSignRotatedValue(uint64_t V);
533
534 /// Materialize any deferred Metadata block.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000535 Error materializeMetadata() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000536
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000537 void setStripDebugInfo() override;
538
Benjamin Kramercced8be2015-03-17 20:40:24 +0000539private:
540 std::vector<StructType *> IdentifiedStructTypes;
541 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
542 StructType *createIdentifiedStructType(LLVMContext &Context);
543
544 Type *getTypeByID(unsigned ID);
Eugene Zelenko1804a772016-08-25 00:45:04 +0000545
David Majnemer8a1c45d2015-12-12 05:38:55 +0000546 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000547 if (Ty && Ty->isMetadataTy())
548 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000549 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000550 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000551
Benjamin Kramercced8be2015-03-17 20:40:24 +0000552 Metadata *getFnMetadataByID(unsigned ID) {
Mehdi Amini3bb4d012017-01-20 20:29:16 +0000553 return MDLoader->getMetadataFwdRefOrLoad(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000554 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000555
Benjamin Kramercced8be2015-03-17 20:40:24 +0000556 BasicBlock *getBasicBlock(unsigned ID) const {
557 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
558 return FunctionBBs[ID];
559 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000560
Reid Klecknerb5180542017-03-21 16:57:19 +0000561 AttributeList getAttributes(unsigned i) const {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000562 if (i-1 < MAttributes.size())
563 return MAttributes[i-1];
Reid Klecknerb5180542017-03-21 16:57:19 +0000564 return AttributeList();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000565 }
566
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000567 /// Read a value/type pair out of the specified record from slot 'Slot'.
568 /// Increment Slot past the number of slots used in the record. Return true on
569 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000570 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
571 unsigned InstNum, Value *&ResVal) {
572 if (Slot == Record.size()) return true;
573 unsigned ValNo = (unsigned)Record[Slot++];
574 // Adjust the ValNo, if it was encoded relative to the InstNum.
575 if (UseRelativeIDs)
576 ValNo = InstNum - ValNo;
577 if (ValNo < InstNum) {
578 // If this is not a forward reference, just return the value we already
579 // have.
580 ResVal = getFnValueByID(ValNo, nullptr);
581 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000582 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000583 if (Slot == Record.size())
584 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000585
586 unsigned TypeNo = (unsigned)Record[Slot++];
587 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
588 return ResVal == nullptr;
589 }
590
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000591 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
592 /// past the number of slots used by the value in the record. Return true if
593 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000594 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000595 unsigned InstNum, Type *Ty, Value *&ResVal) {
596 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000597 return true;
598 // All values currently take a single record slot.
599 ++Slot;
600 return false;
601 }
602
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000603 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000604 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000605 unsigned InstNum, Type *Ty, Value *&ResVal) {
606 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000607 return ResVal == nullptr;
608 }
609
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000610 /// Version of getValue that returns ResVal directly, or 0 if there is an
611 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000612 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000613 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000614 if (Slot == Record.size()) return nullptr;
615 unsigned ValNo = (unsigned)Record[Slot];
616 // Adjust the ValNo, if it was encoded relative to the InstNum.
617 if (UseRelativeIDs)
618 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000619 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000620 }
621
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000622 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000623 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000624 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000625 if (Slot == Record.size()) return nullptr;
626 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
627 // Adjust the ValNo, if it was encoded relative to the InstNum.
628 if (UseRelativeIDs)
629 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000630 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000631 }
632
633 /// Converts alignment exponent (i.e. power of two (or zero)) to the
634 /// corresponding alignment to use. If alignment is too large, returns
635 /// a corresponding error code.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000636 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
637 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
638 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000639
640 Error parseComdatRecord(ArrayRef<uint64_t> Record);
641 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
642 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
643 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
644 ArrayRef<uint64_t> Record);
645
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000646 Error parseAttributeBlock();
647 Error parseAttributeGroupBlock();
648 Error parseTypeTable();
649 Error parseTypeTableBody();
650 Error parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000651
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000652 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
653 unsigned NameIndex, Triple &TT);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000654 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
655 ArrayRef<uint64_t> Record);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000656 Error parseValueSymbolTable(uint64_t Offset = 0);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000657 Error parseGlobalValueSymbolTable();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000658 Error parseConstants();
659 Error rememberAndSkipFunctionBodies();
660 Error rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000661 /// Save the positions of the Metadata blocks and skip parsing the blocks.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000662 Error rememberAndSkipMetadata();
663 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
664 Error parseFunctionBody(Function *F);
665 Error globalCleanup();
666 Error resolveGlobalAndIndirectSymbolInits();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000667 Error parseUseLists();
668 Error findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000669 Function *F,
670 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
671};
Teresa Johnson403a7872015-10-04 14:33:43 +0000672
673/// Class to manage reading and parsing function summary index bitcode
674/// files/sections.
Peter Collingbourne6e860752016-09-23 18:27:42 +0000675class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000676 /// The module index built during parsing.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +0000677 ModuleSummaryIndex &TheIndex;
Teresa Johnson403a7872015-10-04 14:33:43 +0000678
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000679 /// Indicates whether we have encountered a global value summary section
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000680 /// yet during parsing.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000681 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000682
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000683 /// Indicates whether we have already parsed the VST, used for error checking.
684 bool SeenValueSymbolTable = false;
685
686 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
687 /// Used to enable on-demand parsing of the VST.
688 uint64_t VSTOffset = 0;
689
Peter Collingbourne9667b912017-05-04 18:03:25 +0000690 // Map to save ValueId to ValueInfo association that was recorded in the
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000691 // ValueSymbolTable. It is used after the VST is parsed to convert
692 // call graph edges read from the function summary from referencing
Peter Collingbourne9667b912017-05-04 18:03:25 +0000693 // callees by their ValueId to using the ValueInfo instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000694 // they are recorded in the summary index being built.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000695 // We save a GUID which refers to the same global as the ValueInfo, but
696 // ignoring the linkage, i.e. for values other than local linkage they are
697 // identical.
698 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
699 ValueIdToValueInfoMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000700
Teresa Johnson403a7872015-10-04 14:33:43 +0000701 /// Map populated during module path string table parsing, from the
702 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000703 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000704 /// summary records.
705 DenseMap<uint64_t, StringRef> ModuleIdMap;
706
Teresa Johnsone1164de2016-02-10 21:55:02 +0000707 /// Original source file name recorded in a bitcode record.
708 std::string SourceFileName;
709
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000710 /// The string identifier given to this module by the client, normally the
711 /// path to the bitcode file.
712 StringRef ModulePath;
713
714 /// For per-module summary indexes, the unique numerical identifier given to
715 /// this module by the client.
716 unsigned ModuleId;
717
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000718public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000719 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000720 ModuleSummaryIndex &TheIndex,
721 StringRef ModulePath, unsigned ModuleId);
Teresa Johnson403a7872015-10-04 14:33:43 +0000722
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000723 Error parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000724
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000725private:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000726 void setValueGUID(uint64_t ValueID, StringRef ValueName,
727 GlobalValue::LinkageTypes Linkage,
728 StringRef SourceFileName);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000729 Error parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000730 uint64_t Offset,
731 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000732 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
733 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
734 bool IsOldProfileFormat,
735 bool HasProfile);
Peter Collingbournedbd2fed2017-06-15 17:26:13 +0000736 Error parseEntireSummary(unsigned ID);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000737 Error parseModuleStringTable();
Eugene Zelenko1804a772016-08-25 00:45:04 +0000738
Peter Collingbourne9667b912017-05-04 18:03:25 +0000739 std::pair<ValueInfo, GlobalValue::GUID>
740 getValueInfoFromValueId(unsigned ValueId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000741
Peter Collingbourne5aa56d22017-06-14 22:35:27 +0000742 ModuleSummaryIndex::ModuleInfo *addThisModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000743};
Eugene Zelenko1804a772016-08-25 00:45:04 +0000744
Peter Collingbournecd513a42016-11-11 19:50:24 +0000745} // end anonymous namespace
746
747std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
748 Error Err) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000749 if (Err) {
750 std::error_code EC;
751 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
752 EC = EIB.convertToErrorCode();
753 Ctx.emitError(EIB.message());
754 });
755 return EC;
756 }
757 return std::error_code();
758}
759
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000760BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne7a748032016-11-16 21:44:45 +0000761 StringRef ProducerIdentification,
762 LLVMContext &Context)
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000763 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
Mehdi Aminief27db82016-12-12 19:34:26 +0000764 ValueList(Context) {
Peter Collingbourne7a748032016-11-16 21:44:45 +0000765 this->ProducerIdentification = ProducerIdentification;
766}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000767
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000768Error BitcodeReader::materializeForwardReferencedFunctions() {
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000769 if (WillMaterializeAllForwardRefs)
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000770 return Error::success();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000771
772 // Prevent recursion.
773 WillMaterializeAllForwardRefs = true;
774
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000775 while (!BasicBlockFwdRefQueue.empty()) {
776 Function *F = BasicBlockFwdRefQueue.front();
777 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000778 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000779 if (!BasicBlockFwdRefs.count(F))
780 // Already materialized.
781 continue;
782
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000783 // Check for a function that isn't materializable to prevent an infinite
784 // loop. When parsing a blockaddress stored in a global variable, there
785 // isn't a trivial way to check if a function will have a body without a
786 // linear search through FunctionsWithBodies, so just check it here.
787 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000788 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000789
790 // Try to materialize F.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000791 if (Error Err = materialize(F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000792 return Err;
Rafael Espindolab7993462012-01-02 07:49:53 +0000793 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000794 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000795
796 // Reset state.
797 WillMaterializeAllForwardRefs = false;
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000798 return Error::success();
Rafael Espindolab7993462012-01-02 07:49:53 +0000799}
800
Chris Lattnerfee5a372007-05-04 03:30:17 +0000801//===----------------------------------------------------------------------===//
802// Helper functions to implement forward reference resolution, etc.
803//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000804
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000805static bool hasImplicitComdat(size_t Val) {
806 switch (Val) {
807 default:
808 return false;
809 case 1: // Old WeakAnyLinkage
810 case 4: // Old LinkOnceAnyLinkage
811 case 10: // Old WeakODRLinkage
812 case 11: // Old LinkOnceODRLinkage
813 return true;
814 }
815}
816
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000817static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000818 switch (Val) {
819 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000820 case 0:
821 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000822 case 2:
823 return GlobalValue::AppendingLinkage;
824 case 3:
825 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000826 case 5:
827 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
828 case 6:
829 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
830 case 7:
831 return GlobalValue::ExternalWeakLinkage;
832 case 8:
833 return GlobalValue::CommonLinkage;
834 case 9:
835 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000836 case 12:
837 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000838 case 13:
839 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
840 case 14:
841 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000842 case 15:
843 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000844 case 1: // Old value with implicit comdat.
845 case 16:
846 return GlobalValue::WeakAnyLinkage;
847 case 10: // Old value with implicit comdat.
848 case 17:
849 return GlobalValue::WeakODRLinkage;
850 case 4: // Old value with implicit comdat.
851 case 18:
852 return GlobalValue::LinkOnceAnyLinkage;
853 case 11: // Old value with implicit comdat.
854 case 19:
855 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000856 }
857}
858
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000859/// Decode the flags for GlobalValue in the summary.
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000860static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
861 uint64_t Version) {
862 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
863 // like getDecodedLinkage() above. Any future change to the linkage enum and
864 // to getDecodedLinkage() will need to be taken into account here as above.
865 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Amini1380edf2017-02-03 07:41:43 +0000866 RawFlags = RawFlags >> 4;
867 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000868 // The Live flag wasn't introduced until version 3. For dead stripping
Teresa Johnson6c475a72017-01-05 21:34:18 +0000869 // to work correctly on earlier versions, we must conservatively treat all
870 // values as live.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000871 bool Live = (RawFlags & 0x2) || Version < 3;
872 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000873}
874
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000875static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000876 switch (Val) {
877 default: // Map unknown visibilities to default.
878 case 0: return GlobalValue::DefaultVisibility;
879 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000880 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000881 }
882}
883
Nico Rieck7157bb72014-01-14 15:22:47 +0000884static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000885getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000886 switch (Val) {
887 default: // Map unknown values to default.
888 case 0: return GlobalValue::DefaultStorageClass;
889 case 1: return GlobalValue::DLLImportStorageClass;
890 case 2: return GlobalValue::DLLExportStorageClass;
891 }
892}
893
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000894static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000895 switch (Val) {
896 case 0: return GlobalVariable::NotThreadLocal;
897 default: // Map unknown non-zero value to general dynamic.
898 case 1: return GlobalVariable::GeneralDynamicTLSModel;
899 case 2: return GlobalVariable::LocalDynamicTLSModel;
900 case 3: return GlobalVariable::InitialExecTLSModel;
901 case 4: return GlobalVariable::LocalExecTLSModel;
902 }
903}
904
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000905static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
906 switch (Val) {
907 default: // Map unknown to UnnamedAddr::None.
908 case 0: return GlobalVariable::UnnamedAddr::None;
909 case 1: return GlobalVariable::UnnamedAddr::Global;
910 case 2: return GlobalVariable::UnnamedAddr::Local;
911 }
912}
913
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000914static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000915 switch (Val) {
916 default: return -1;
917 case bitc::CAST_TRUNC : return Instruction::Trunc;
918 case bitc::CAST_ZEXT : return Instruction::ZExt;
919 case bitc::CAST_SEXT : return Instruction::SExt;
920 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
921 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
922 case bitc::CAST_UITOFP : return Instruction::UIToFP;
923 case bitc::CAST_SITOFP : return Instruction::SIToFP;
924 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
925 case bitc::CAST_FPEXT : return Instruction::FPExt;
926 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
927 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
928 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000929 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000930 }
931}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000932
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000933static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000934 bool IsFP = Ty->isFPOrFPVectorTy();
935 // BinOps are only valid for int/fp or vector of int/fp types
936 if (!IsFP && !Ty->isIntOrIntVectorTy())
937 return -1;
938
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000939 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000940 default:
941 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000942 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000943 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000944 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000945 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000946 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000947 return IsFP ? Instruction::FMul : Instruction::Mul;
948 case bitc::BINOP_UDIV:
949 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000950 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000951 return IsFP ? Instruction::FDiv : Instruction::SDiv;
952 case bitc::BINOP_UREM:
953 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000954 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000955 return IsFP ? Instruction::FRem : Instruction::SRem;
956 case bitc::BINOP_SHL:
957 return IsFP ? -1 : Instruction::Shl;
958 case bitc::BINOP_LSHR:
959 return IsFP ? -1 : Instruction::LShr;
960 case bitc::BINOP_ASHR:
961 return IsFP ? -1 : Instruction::AShr;
962 case bitc::BINOP_AND:
963 return IsFP ? -1 : Instruction::And;
964 case bitc::BINOP_OR:
965 return IsFP ? -1 : Instruction::Or;
966 case bitc::BINOP_XOR:
967 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000968 }
969}
970
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000971static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000972 switch (Val) {
973 default: return AtomicRMWInst::BAD_BINOP;
974 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
975 case bitc::RMW_ADD: return AtomicRMWInst::Add;
976 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
977 case bitc::RMW_AND: return AtomicRMWInst::And;
978 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
979 case bitc::RMW_OR: return AtomicRMWInst::Or;
980 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
981 case bitc::RMW_MAX: return AtomicRMWInst::Max;
982 case bitc::RMW_MIN: return AtomicRMWInst::Min;
983 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
984 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
985 }
986}
987
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000988static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000989 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +0000990 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
991 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
992 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
993 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
994 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
995 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000996 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +0000997 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000998 }
999}
1000
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001001static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001002 switch (Val) {
1003 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
1004 default: // Map unknown scopes to cross-thread.
1005 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
1006 }
1007}
1008
David Majnemerdad0a642014-06-27 18:19:56 +00001009static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1010 switch (Val) {
1011 default: // Map unknown selection kinds to any.
1012 case bitc::COMDAT_SELECTION_KIND_ANY:
1013 return Comdat::Any;
1014 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1015 return Comdat::ExactMatch;
1016 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1017 return Comdat::Largest;
1018 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1019 return Comdat::NoDuplicates;
1020 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1021 return Comdat::SameSize;
1022 }
1023}
1024
James Molloy88eb5352015-07-10 12:52:00 +00001025static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1026 FastMathFlags FMF;
1027 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
1028 FMF.setUnsafeAlgebra();
1029 if (0 != (Val & FastMathFlags::NoNaNs))
1030 FMF.setNoNaNs();
1031 if (0 != (Val & FastMathFlags::NoInfs))
1032 FMF.setNoInfs();
1033 if (0 != (Val & FastMathFlags::NoSignedZeros))
1034 FMF.setNoSignedZeros();
1035 if (0 != (Val & FastMathFlags::AllowReciprocal))
1036 FMF.setAllowReciprocal();
Adam Nemetcd847a82017-03-28 20:11:52 +00001037 if (0 != (Val & FastMathFlags::AllowContract))
1038 FMF.setAllowContract(true);
James Molloy88eb5352015-07-10 12:52:00 +00001039 return FMF;
1040}
1041
Eugene Zelenko1804a772016-08-25 00:45:04 +00001042static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001043 switch (Val) {
1044 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1045 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1046 }
1047}
1048
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001049
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001050Type *BitcodeReader::getTypeByID(unsigned ID) {
1051 // The type table size is always specified correctly.
1052 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001053 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001054
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001055 if (Type *Ty = TypeList[ID])
1056 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001057
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001058 // If we have a forward reference, the only possible case is when it is to a
1059 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001060 return TypeList[ID] = createIdentifiedStructType(Context);
1061}
1062
1063StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1064 StringRef Name) {
1065 auto *Ret = StructType::create(Context, Name);
1066 IdentifiedStructTypes.push_back(Ret);
1067 return Ret;
1068}
1069
1070StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1071 auto *Ret = StructType::create(Context);
1072 IdentifiedStructTypes.push_back(Ret);
1073 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001074}
1075
Chris Lattnerfee5a372007-05-04 03:30:17 +00001076//===----------------------------------------------------------------------===//
1077// Functions for parsing blocks from the bitcode file
1078//===----------------------------------------------------------------------===//
1079
Amaury Sechet74084c42016-11-06 07:48:46 +00001080static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1081 switch (Val) {
1082 case Attribute::EndAttrKinds:
1083 llvm_unreachable("Synthetic enumerators which should never get here");
1084
1085 case Attribute::None: return 0;
1086 case Attribute::ZExt: return 1 << 0;
1087 case Attribute::SExt: return 1 << 1;
1088 case Attribute::NoReturn: return 1 << 2;
1089 case Attribute::InReg: return 1 << 3;
1090 case Attribute::StructRet: return 1 << 4;
1091 case Attribute::NoUnwind: return 1 << 5;
1092 case Attribute::NoAlias: return 1 << 6;
1093 case Attribute::ByVal: return 1 << 7;
1094 case Attribute::Nest: return 1 << 8;
1095 case Attribute::ReadNone: return 1 << 9;
1096 case Attribute::ReadOnly: return 1 << 10;
1097 case Attribute::NoInline: return 1 << 11;
1098 case Attribute::AlwaysInline: return 1 << 12;
1099 case Attribute::OptimizeForSize: return 1 << 13;
1100 case Attribute::StackProtect: return 1 << 14;
1101 case Attribute::StackProtectReq: return 1 << 15;
1102 case Attribute::Alignment: return 31 << 16;
1103 case Attribute::NoCapture: return 1 << 21;
1104 case Attribute::NoRedZone: return 1 << 22;
1105 case Attribute::NoImplicitFloat: return 1 << 23;
1106 case Attribute::Naked: return 1 << 24;
1107 case Attribute::InlineHint: return 1 << 25;
1108 case Attribute::StackAlignment: return 7 << 26;
1109 case Attribute::ReturnsTwice: return 1 << 29;
1110 case Attribute::UWTable: return 1 << 30;
1111 case Attribute::NonLazyBind: return 1U << 31;
1112 case Attribute::SanitizeAddress: return 1ULL << 32;
1113 case Attribute::MinSize: return 1ULL << 33;
1114 case Attribute::NoDuplicate: return 1ULL << 34;
1115 case Attribute::StackProtectStrong: return 1ULL << 35;
1116 case Attribute::SanitizeThread: return 1ULL << 36;
1117 case Attribute::SanitizeMemory: return 1ULL << 37;
1118 case Attribute::NoBuiltin: return 1ULL << 38;
1119 case Attribute::Returned: return 1ULL << 39;
1120 case Attribute::Cold: return 1ULL << 40;
1121 case Attribute::Builtin: return 1ULL << 41;
1122 case Attribute::OptimizeNone: return 1ULL << 42;
1123 case Attribute::InAlloca: return 1ULL << 43;
1124 case Attribute::NonNull: return 1ULL << 44;
1125 case Attribute::JumpTable: return 1ULL << 45;
1126 case Attribute::Convergent: return 1ULL << 46;
1127 case Attribute::SafeStack: return 1ULL << 47;
1128 case Attribute::NoRecurse: return 1ULL << 48;
1129 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1130 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1131 case Attribute::SwiftSelf: return 1ULL << 51;
1132 case Attribute::SwiftError: return 1ULL << 52;
1133 case Attribute::WriteOnly: return 1ULL << 53;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001134 case Attribute::Speculatable: return 1ULL << 54;
Amaury Sechet74084c42016-11-06 07:48:46 +00001135 case Attribute::Dereferenceable:
1136 llvm_unreachable("dereferenceable attribute not supported in raw format");
1137 break;
1138 case Attribute::DereferenceableOrNull:
1139 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1140 "format");
1141 break;
1142 case Attribute::ArgMemOnly:
1143 llvm_unreachable("argmemonly attribute not supported in raw format");
1144 break;
1145 case Attribute::AllocSize:
1146 llvm_unreachable("allocsize not supported in raw format");
1147 break;
1148 }
1149 llvm_unreachable("Unsupported attribute type");
1150}
1151
1152static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1153 if (!Val) return;
1154
1155 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1156 I = Attribute::AttrKind(I + 1)) {
1157 if (I == Attribute::Dereferenceable ||
1158 I == Attribute::DereferenceableOrNull ||
1159 I == Attribute::ArgMemOnly ||
1160 I == Attribute::AllocSize)
1161 continue;
1162 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1163 if (I == Attribute::Alignment)
1164 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1165 else if (I == Attribute::StackAlignment)
1166 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1167 else
1168 B.addAttribute(I);
1169 }
1170 }
1171}
1172
Bill Wendling56aeccc2013-02-04 23:32:23 +00001173/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1174/// been decoded from the given integer. This function must stay in sync with
1175/// 'encodeLLVMAttributesForBitcode'.
1176static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1177 uint64_t EncodedAttrs) {
1178 // FIXME: Remove in 4.0.
1179
1180 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1181 // the bits above 31 down by 11 bits.
1182 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1183 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1184 "Alignment must be a power of two.");
1185
1186 if (Alignment)
1187 B.addAlignmentAttr(Alignment);
Amaury Sechet74084c42016-11-06 07:48:46 +00001188 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1189 (EncodedAttrs & 0xffff));
Bill Wendling56aeccc2013-02-04 23:32:23 +00001190}
1191
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001192Error BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001193 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001194 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001195
Devang Patela05633e2008-09-26 22:53:05 +00001196 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001197 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001198
Chris Lattnerfee5a372007-05-04 03:30:17 +00001199 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001200
Reid Klecknerb5180542017-03-21 16:57:19 +00001201 SmallVector<AttributeList, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001202
Chris Lattnerfee5a372007-05-04 03:30:17 +00001203 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001204 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001205 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001206
Chris Lattner27d38752013-01-20 02:13:19 +00001207 switch (Entry.Kind) {
1208 case BitstreamEntry::SubBlock: // Handled for us already.
1209 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001210 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001211 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001212 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001213 case BitstreamEntry::Record:
1214 // The interesting case.
1215 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001216 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001217
Chris Lattnerfee5a372007-05-04 03:30:17 +00001218 // Read a record.
1219 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001220 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001221 default: // Default behavior: ignore.
1222 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001223 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1224 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001225 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001226 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001227
Chris Lattnerfee5a372007-05-04 03:30:17 +00001228 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001229 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001230 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Reid Klecknerb5180542017-03-21 16:57:19 +00001231 Attrs.push_back(AttributeList::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001232 }
Devang Patela05633e2008-09-26 22:53:05 +00001233
Reid Klecknerb5180542017-03-21 16:57:19 +00001234 MAttributes.push_back(AttributeList::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001235 Attrs.clear();
1236 break;
1237 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001238 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1239 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1240 Attrs.push_back(MAttributeGroups[Record[i]]);
1241
Reid Klecknerb5180542017-03-21 16:57:19 +00001242 MAttributes.push_back(AttributeList::get(Context, Attrs));
Bill Wendling0dc08912013-02-12 08:13:50 +00001243 Attrs.clear();
1244 break;
1245 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001246 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001247 }
1248}
1249
Reid Klecknere9f36af2013-11-12 01:31:00 +00001250// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001251static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001252 switch (Code) {
1253 default:
1254 return Attribute::None;
1255 case bitc::ATTR_KIND_ALIGNMENT:
1256 return Attribute::Alignment;
1257 case bitc::ATTR_KIND_ALWAYS_INLINE:
1258 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001259 case bitc::ATTR_KIND_ARGMEMONLY:
1260 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001261 case bitc::ATTR_KIND_BUILTIN:
1262 return Attribute::Builtin;
1263 case bitc::ATTR_KIND_BY_VAL:
1264 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001265 case bitc::ATTR_KIND_IN_ALLOCA:
1266 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001267 case bitc::ATTR_KIND_COLD:
1268 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001269 case bitc::ATTR_KIND_CONVERGENT:
1270 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001271 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1272 return Attribute::InaccessibleMemOnly;
1273 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1274 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001275 case bitc::ATTR_KIND_INLINE_HINT:
1276 return Attribute::InlineHint;
1277 case bitc::ATTR_KIND_IN_REG:
1278 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001279 case bitc::ATTR_KIND_JUMP_TABLE:
1280 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001281 case bitc::ATTR_KIND_MIN_SIZE:
1282 return Attribute::MinSize;
1283 case bitc::ATTR_KIND_NAKED:
1284 return Attribute::Naked;
1285 case bitc::ATTR_KIND_NEST:
1286 return Attribute::Nest;
1287 case bitc::ATTR_KIND_NO_ALIAS:
1288 return Attribute::NoAlias;
1289 case bitc::ATTR_KIND_NO_BUILTIN:
1290 return Attribute::NoBuiltin;
1291 case bitc::ATTR_KIND_NO_CAPTURE:
1292 return Attribute::NoCapture;
1293 case bitc::ATTR_KIND_NO_DUPLICATE:
1294 return Attribute::NoDuplicate;
1295 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1296 return Attribute::NoImplicitFloat;
1297 case bitc::ATTR_KIND_NO_INLINE:
1298 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001299 case bitc::ATTR_KIND_NO_RECURSE:
1300 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001301 case bitc::ATTR_KIND_NON_LAZY_BIND:
1302 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001303 case bitc::ATTR_KIND_NON_NULL:
1304 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001305 case bitc::ATTR_KIND_DEREFERENCEABLE:
1306 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001307 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1308 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001309 case bitc::ATTR_KIND_ALLOC_SIZE:
1310 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001311 case bitc::ATTR_KIND_NO_RED_ZONE:
1312 return Attribute::NoRedZone;
1313 case bitc::ATTR_KIND_NO_RETURN:
1314 return Attribute::NoReturn;
1315 case bitc::ATTR_KIND_NO_UNWIND:
1316 return Attribute::NoUnwind;
1317 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1318 return Attribute::OptimizeForSize;
1319 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1320 return Attribute::OptimizeNone;
1321 case bitc::ATTR_KIND_READ_NONE:
1322 return Attribute::ReadNone;
1323 case bitc::ATTR_KIND_READ_ONLY:
1324 return Attribute::ReadOnly;
1325 case bitc::ATTR_KIND_RETURNED:
1326 return Attribute::Returned;
1327 case bitc::ATTR_KIND_RETURNS_TWICE:
1328 return Attribute::ReturnsTwice;
1329 case bitc::ATTR_KIND_S_EXT:
1330 return Attribute::SExt;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001331 case bitc::ATTR_KIND_SPECULATABLE:
1332 return Attribute::Speculatable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001333 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1334 return Attribute::StackAlignment;
1335 case bitc::ATTR_KIND_STACK_PROTECT:
1336 return Attribute::StackProtect;
1337 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1338 return Attribute::StackProtectReq;
1339 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1340 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001341 case bitc::ATTR_KIND_SAFESTACK:
1342 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001343 case bitc::ATTR_KIND_STRUCT_RET:
1344 return Attribute::StructRet;
1345 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1346 return Attribute::SanitizeAddress;
1347 case bitc::ATTR_KIND_SANITIZE_THREAD:
1348 return Attribute::SanitizeThread;
1349 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1350 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001351 case bitc::ATTR_KIND_SWIFT_ERROR:
1352 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001353 case bitc::ATTR_KIND_SWIFT_SELF:
1354 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001355 case bitc::ATTR_KIND_UW_TABLE:
1356 return Attribute::UWTable;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001357 case bitc::ATTR_KIND_WRITEONLY:
1358 return Attribute::WriteOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001359 case bitc::ATTR_KIND_Z_EXT:
1360 return Attribute::ZExt;
1361 }
1362}
1363
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001364Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1365 unsigned &Alignment) {
JF Bastien30bf96b2015-02-22 19:32:03 +00001366 // Note: Alignment in bitcode files is incremented by 1, so that zero
1367 // can be used for default alignment.
1368 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001369 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001370 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001371 return Error::success();
JF Bastien30bf96b2015-02-22 19:32:03 +00001372}
1373
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001374Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001375 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001376 if (*Kind == Attribute::None)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001377 return error("Unknown attribute kind (" + Twine(Code) + ")");
1378 return Error::success();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001379}
1380
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001381Error BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001382 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001383 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001384
1385 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001386 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001387
1388 SmallVector<uint64_t, 64> Record;
1389
1390 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001391 while (true) {
Bill Wendlingba629332013-02-10 23:24:25 +00001392 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1393
1394 switch (Entry.Kind) {
1395 case BitstreamEntry::SubBlock: // Handled for us already.
1396 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001397 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001398 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001399 return Error::success();
Bill Wendlingba629332013-02-10 23:24:25 +00001400 case BitstreamEntry::Record:
1401 // The interesting case.
1402 break;
1403 }
1404
1405 // Read a record.
1406 Record.clear();
1407 switch (Stream.readRecord(Entry.ID, Record)) {
1408 default: // Default behavior: ignore.
1409 break;
1410 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1411 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001412 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001413
Bill Wendlinge46707e2013-02-11 22:32:29 +00001414 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001415 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1416
1417 AttrBuilder B;
1418 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1419 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001420 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001421 if (Error Err = parseAttrKind(Record[++i], &Kind))
1422 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001423
1424 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001425 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001426 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001427 if (Error Err = parseAttrKind(Record[++i], &Kind))
1428 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001429 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001430 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001431 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001432 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001433 else if (Kind == Attribute::Dereferenceable)
1434 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001435 else if (Kind == Attribute::DereferenceableOrNull)
1436 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001437 else if (Kind == Attribute::AllocSize)
1438 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001439 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001440 assert((Record[i] == 3 || Record[i] == 4) &&
1441 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001442 bool HasValue = (Record[i++] == 4);
1443 SmallString<64> KindStr;
1444 SmallString<64> ValStr;
1445
1446 while (Record[i] != 0 && i != e)
1447 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001448 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001449
1450 if (HasValue) {
1451 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001452 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001453 while (Record[i] != 0 && i != e)
1454 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001455 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001456 }
1457
1458 B.addAttribute(KindStr.str(), ValStr.str());
1459 }
1460 }
1461
Reid Klecknerb5180542017-03-21 16:57:19 +00001462 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001463 break;
1464 }
1465 }
1466 }
1467}
1468
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001469Error BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001470 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001471 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001472
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001473 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001474}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001475
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001476Error BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001477 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001478 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001479
1480 SmallVector<uint64_t, 64> Record;
1481 unsigned NumRecords = 0;
1482
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001483 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001484
Chris Lattner1314b992007-04-22 06:23:29 +00001485 // Read all the records for this type table.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001486 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001487 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001488
Chris Lattner27d38752013-01-20 02:13:19 +00001489 switch (Entry.Kind) {
1490 case BitstreamEntry::SubBlock: // Handled for us already.
1491 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001492 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001493 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001494 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001495 return error("Malformed block");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001496 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001497 case BitstreamEntry::Record:
1498 // The interesting case.
1499 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001500 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001501
Chris Lattner1314b992007-04-22 06:23:29 +00001502 // Read a record.
1503 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001504 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001505 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001506 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001507 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001508 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1509 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1510 // type list. This allows us to reserve space.
1511 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001512 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001513 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001514 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001515 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001516 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001517 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001518 case bitc::TYPE_CODE_HALF: // HALF
1519 ResultTy = Type::getHalfTy(Context);
1520 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001521 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001522 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001523 break;
1524 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001525 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001526 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001527 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001528 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001529 break;
1530 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001531 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001532 break;
1533 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001534 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001535 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001536 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001537 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001538 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001539 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001540 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001541 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001542 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1543 ResultTy = Type::getX86_MMXTy(Context);
1544 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001545 case bitc::TYPE_CODE_TOKEN: // TOKEN
1546 ResultTy = Type::getTokenTy(Context);
1547 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001548 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001549 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001550 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001551
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001552 uint64_t NumBits = Record[0];
1553 if (NumBits < IntegerType::MIN_INT_BITS ||
1554 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001555 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001556 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001557 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001558 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001559 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001560 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001561 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001562 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001563 unsigned AddressSpace = 0;
1564 if (Record.size() == 2)
1565 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001566 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001567 if (!ResultTy ||
1568 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001569 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001570 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001571 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001572 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001573 case bitc::TYPE_CODE_FUNCTION_OLD: {
1574 // FIXME: attrid is dead, remove it in LLVM 4.0
1575 // FUNCTION: [vararg, attrid, retty, paramty x N]
1576 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001577 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001578 SmallVector<Type*, 8> ArgTys;
1579 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1580 if (Type *T = getTypeByID(Record[i]))
1581 ArgTys.push_back(T);
1582 else
1583 break;
1584 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001585
Nuno Lopes561dae02012-05-23 15:19:39 +00001586 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001587 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001588 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001589
1590 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1591 break;
1592 }
Chad Rosier95898722011-11-03 00:14:01 +00001593 case bitc::TYPE_CODE_FUNCTION: {
1594 // FUNCTION: [vararg, retty, paramty x N]
1595 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001596 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001597 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001598 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001599 if (Type *T = getTypeByID(Record[i])) {
1600 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001601 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001602 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001603 }
Chad Rosier95898722011-11-03 00:14:01 +00001604 else
1605 break;
1606 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001607
Chad Rosier95898722011-11-03 00:14:01 +00001608 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001609 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001610 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001611
1612 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1613 break;
1614 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001615 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001616 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001617 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001618 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001619 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1620 if (Type *T = getTypeByID(Record[i]))
1621 EltTys.push_back(T);
1622 else
1623 break;
1624 }
1625 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001626 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001627 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001628 break;
1629 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001630 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001631 if (convertToString(Record, 0, TypeName))
1632 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001633 continue;
1634
1635 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1636 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001637 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001638
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001639 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001640 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001641
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001642 // Check to see if this was forward referenced, if so fill in the temp.
1643 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1644 if (Res) {
1645 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001646 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001647 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001648 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001649 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001650
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001651 SmallVector<Type*, 8> EltTys;
1652 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1653 if (Type *T = getTypeByID(Record[i]))
1654 EltTys.push_back(T);
1655 else
1656 break;
1657 }
1658 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001659 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001660 Res->setBody(EltTys, Record[0]);
1661 ResultTy = Res;
1662 break;
1663 }
1664 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1665 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001666 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001667
1668 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001669 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001670
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001671 // Check to see if this was forward referenced, if so fill in the temp.
1672 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1673 if (Res) {
1674 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001675 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001676 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001677 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001678 TypeName.clear();
1679 ResultTy = Res;
1680 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001681 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001682 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1683 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001684 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001685 ResultTy = getTypeByID(Record[1]);
1686 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001687 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001688 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001689 break;
1690 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1691 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001692 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001693 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001694 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001695 ResultTy = getTypeByID(Record[1]);
1696 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001697 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001698 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001699 break;
1700 }
1701
1702 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001703 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001704 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001705 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001706 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001707 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001708 TypeList[NumRecords++] = ResultTy;
1709 }
1710}
1711
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001712Error BitcodeReader::parseOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001713 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1714 return error("Invalid record");
1715
1716 if (!BundleTags.empty())
1717 return error("Invalid multiple blocks");
1718
1719 SmallVector<uint64_t, 64> Record;
1720
Eugene Zelenko1804a772016-08-25 00:45:04 +00001721 while (true) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001722 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1723
1724 switch (Entry.Kind) {
1725 case BitstreamEntry::SubBlock: // Handled for us already.
1726 case BitstreamEntry::Error:
1727 return error("Malformed block");
1728 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001729 return Error::success();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001730 case BitstreamEntry::Record:
1731 // The interesting case.
1732 break;
1733 }
1734
1735 // Tags are implicitly mapped to integers by their order.
1736
1737 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1738 return error("Invalid record");
1739
1740 // OPERAND_BUNDLE_TAG: [strchr x N]
1741 BundleTags.emplace_back();
1742 if (convertToString(Record, 0, BundleTags.back()))
1743 return error("Invalid record");
1744 Record.clear();
1745 }
1746}
1747
Teresa Johnsonff642b92015-09-17 20:12:00 +00001748/// Associate a value with its name from the given index in the provided record.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001749Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1750 unsigned NameIndex, Triple &TT) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001751 SmallString<128> ValueName;
1752 if (convertToString(Record, NameIndex, ValueName))
1753 return error("Invalid record");
1754 unsigned ValueID = Record[0];
1755 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1756 return error("Invalid record");
1757 Value *V = ValueList[ValueID];
1758
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001759 StringRef NameStr(ValueName.data(), ValueName.size());
1760 if (NameStr.find_first_of(0) != StringRef::npos)
1761 return error("Invalid value name");
1762 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001763 auto *GO = dyn_cast<GlobalObject>(V);
1764 if (GO) {
1765 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1766 if (TT.isOSBinFormatMachO())
1767 GO->setComdat(nullptr);
1768 else
1769 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1770 }
1771 }
1772 return V;
1773}
1774
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001775/// Helper to note and return the current location, and jump to the given
1776/// offset.
1777static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1778 BitstreamCursor &Stream) {
1779 // Save the current parsing location so we can jump back at the end
1780 // of the VST read.
1781 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1782 Stream.JumpToBit(Offset * 32);
1783#ifndef NDEBUG
1784 // Do some checking if we are in debug mode.
1785 BitstreamEntry Entry = Stream.advance();
1786 assert(Entry.Kind == BitstreamEntry::SubBlock);
1787 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1788#else
1789 // In NDEBUG mode ignore the output so we don't get an unused variable
1790 // warning.
1791 Stream.advance();
1792#endif
1793 return CurrentBit;
1794}
1795
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001796void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1797 Function *F,
1798 ArrayRef<uint64_t> Record) {
1799 // Note that we subtract 1 here because the offset is relative to one word
1800 // before the start of the identification or module block, which was
1801 // historically always the start of the regular bitcode header.
1802 uint64_t FuncWordOffset = Record[1] - 1;
1803 uint64_t FuncBitOffset = FuncWordOffset * 32;
1804 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1805 // Set the LastFunctionBlockBit to point to the last function block.
1806 // Later when parsing is resumed after function materialization,
1807 // we can simply skip that last function block.
1808 if (FuncBitOffset > LastFunctionBlockBit)
1809 LastFunctionBlockBit = FuncBitOffset;
1810}
1811
1812/// Read a new-style GlobalValue symbol table.
1813Error BitcodeReader::parseGlobalValueSymbolTable() {
1814 unsigned FuncBitcodeOffsetDelta =
1815 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1816
1817 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1818 return error("Invalid record");
1819
1820 SmallVector<uint64_t, 64> Record;
1821 while (true) {
1822 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1823
1824 switch (Entry.Kind) {
1825 case BitstreamEntry::SubBlock:
1826 case BitstreamEntry::Error:
1827 return error("Malformed block");
1828 case BitstreamEntry::EndBlock:
1829 return Error::success();
1830 case BitstreamEntry::Record:
1831 break;
1832 }
1833
1834 Record.clear();
1835 switch (Stream.readRecord(Entry.ID, Record)) {
1836 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1837 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1838 cast<Function>(ValueList[Record[0]]), Record);
1839 break;
1840 }
1841 }
1842}
1843
Teresa Johnsonff642b92015-09-17 20:12:00 +00001844/// Parse the value symbol table at either the current parsing location or
1845/// at the given bit offset if provided.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001846Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001847 uint64_t CurrentBit;
1848 // Pass in the Offset to distinguish between calling for the module-level
1849 // VST (where we want to jump to the VST offset) and the function-level
1850 // VST (where we don't).
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001851 if (Offset > 0) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001852 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001853 // If this module uses a string table, read this as a module-level VST.
1854 if (UseStrtab) {
1855 if (Error Err = parseGlobalValueSymbolTable())
1856 return Err;
1857 Stream.JumpToBit(CurrentBit);
1858 return Error::success();
1859 }
1860 // Otherwise, the VST will be in a similar format to a function-level VST,
1861 // and will contain symbol names.
1862 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001863
1864 // Compute the delta between the bitcode indices in the VST (the word offset
1865 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1866 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1867 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1868 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1869 // just before entering the VST subblock because: 1) the EnterSubBlock
1870 // changes the AbbrevID width; 2) the VST block is nested within the same
1871 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1872 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1873 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1874 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1875 unsigned FuncBitcodeOffsetDelta =
1876 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1877
Chris Lattner982ec1e2007-05-05 00:17:00 +00001878 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001879 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001880
1881 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001882
David Majnemer3087b222015-01-20 05:58:07 +00001883 Triple TT(TheModule->getTargetTriple());
1884
Chris Lattnerccaa4482007-04-23 21:26:05 +00001885 // Read all the records for this value table.
1886 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00001887
1888 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001889 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001890
Chris Lattner27d38752013-01-20 02:13:19 +00001891 switch (Entry.Kind) {
1892 case BitstreamEntry::SubBlock: // Handled for us already.
1893 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001894 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001895 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001896 if (Offset > 0)
1897 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001898 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001899 case BitstreamEntry::Record:
1900 // The interesting case.
1901 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001903
Chris Lattnerccaa4482007-04-23 21:26:05 +00001904 // Read a record.
1905 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001906 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001907 default: // Default behavior: unknown type.
1908 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001909 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001910 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1911 if (Error Err = ValOrErr.takeError())
1912 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001913 ValOrErr.get();
1914 break;
1915 }
1916 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001917 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001918 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1919 if (Error Err = ValOrErr.takeError())
1920 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001921 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001922
Peter Collingbournedb4cafa2017-04-06 19:39:24 +00001923 // Ignore function offsets emitted for aliases of functions in older
1924 // versions of LLVM.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001925 if (auto *F = dyn_cast<Function>(V))
1926 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001927 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001928 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001929 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001930 if (convertToString(Record, 1, ValueName))
1931 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001932 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001933 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001934 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001935
Daniel Dunbard786b512009-07-26 00:34:27 +00001936 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001937 ValueName.clear();
1938 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001939 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001940 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001941 }
1942}
1943
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001944/// Decode a signed value stored with the sign bit in the LSB for dense VBR
1945/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001946uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001947 if ((V & 1) == 0)
1948 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001949 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001950 return -(V >> 1);
1951 // There is no such thing as -0 with integers. "-0" really means MININT.
1952 return 1ULL << 63;
1953}
1954
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001955/// Resolve all of the initializers for global values and aliases that we can.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001956Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00001957 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001958 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
1959 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001960 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001961 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00001962 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001963
Chris Lattner44c17072007-04-26 02:46:40 +00001964 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001965 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001966 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001967 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00001968 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00001969
1970 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00001971 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001972 if (ValID >= ValueList.size()) {
1973 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00001974 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001975 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001976 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00001977 GlobalInitWorklist.back().first->setInitializer(C);
1978 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001979 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00001980 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001981 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001982 }
1983
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001984 while (!IndirectSymbolInitWorklist.empty()) {
1985 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001986 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001987 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001988 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00001989 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
1990 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001991 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001992 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
1993 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001994 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001995 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00001996 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00001997 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001998 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001999
2000 while (!FunctionPrefixWorklist.empty()) {
2001 unsigned ValID = FunctionPrefixWorklist.back().second;
2002 if (ValID >= ValueList.size()) {
2003 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2004 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002005 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002006 FunctionPrefixWorklist.back().first->setPrefixData(C);
2007 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002008 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002009 }
2010 FunctionPrefixWorklist.pop_back();
2011 }
2012
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002013 while (!FunctionPrologueWorklist.empty()) {
2014 unsigned ValID = FunctionPrologueWorklist.back().second;
2015 if (ValID >= ValueList.size()) {
2016 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2017 } else {
2018 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2019 FunctionPrologueWorklist.back().first->setPrologueData(C);
2020 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002021 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002022 }
2023 FunctionPrologueWorklist.pop_back();
2024 }
2025
David Majnemer7fddecc2015-06-17 20:52:32 +00002026 while (!FunctionPersonalityFnWorklist.empty()) {
2027 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2028 if (ValID >= ValueList.size()) {
2029 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2030 } else {
2031 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2032 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2033 else
2034 return error("Expected a constant");
2035 }
2036 FunctionPersonalityFnWorklist.pop_back();
2037 }
2038
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002039 return Error::success();
Chris Lattner44c17072007-04-26 02:46:40 +00002040}
2041
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002042static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002043 SmallVector<uint64_t, 8> Words(Vals.size());
David Majnemer2d006e72016-08-12 04:32:42 +00002044 transform(Vals, Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002045 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002046
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002047 return APInt(TypeBits, Words);
2048}
2049
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002050Error BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002051 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002052 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002053
2054 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002055
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002056 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002057 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002058 unsigned NextCstNo = ValueList.size();
Eugene Zelenko1804a772016-08-25 00:45:04 +00002059
2060 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002061 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002062
Chris Lattner27d38752013-01-20 02:13:19 +00002063 switch (Entry.Kind) {
2064 case BitstreamEntry::SubBlock: // Handled for us already.
2065 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002066 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002067 case BitstreamEntry::EndBlock:
2068 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002069 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002070
Chris Lattner27d38752013-01-20 02:13:19 +00002071 // Once all the constants have been read, go through and resolve forward
2072 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002073 ValueList.resolveConstantForwardRefs();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002074 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002075 case BitstreamEntry::Record:
2076 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002077 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002078 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002079
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002080 // Read a record.
2081 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002082 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002083 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002084 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002085 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002086 default: // Default behavior: unknown constant
2087 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002088 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002089 break;
2090 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2091 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002092 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002093 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002094 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002095 if (TypeList[Record[0]] == VoidType)
2096 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002097 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002098 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002099 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002100 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002101 break;
2102 case bitc::CST_CODE_INTEGER: // INTEGER: [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");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002105 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002106 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002107 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002108 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002109 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002110
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002111 APInt VInt =
2112 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002113 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002114
Chris Lattner08feb1e2007-04-24 04:04:35 +00002115 break;
2116 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002117 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002118 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002119 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002120 if (CurTy->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002121 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
Tim Northover29178a32013-01-22 09:46:31 +00002122 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002123 else if (CurTy->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002124 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
Tim Northover29178a32013-01-22 09:46:31 +00002125 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002126 else if (CurTy->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002127 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002128 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002129 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002130 // Bits are not stored the same way as a normal i80 APInt, compensate.
2131 uint64_t Rearrange[2];
2132 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2133 Rearrange[1] = Record[0] >> 48;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002134 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
Tim Northover29178a32013-01-22 09:46:31 +00002135 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002136 } else if (CurTy->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002137 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
Tim Northover29178a32013-01-22 09:46:31 +00002138 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002139 else if (CurTy->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002140 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002141 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002142 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002143 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002144 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002145 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002146
Chris Lattnere14cb882007-05-04 19:11:41 +00002147 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2148 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002149 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002150
Chris Lattnere14cb882007-05-04 19:11:41 +00002151 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002152 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002153
Chris Lattner229907c2011-07-18 04:54:35 +00002154 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002155 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002156 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002157 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002158 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002159 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2160 Type *EltTy = ATy->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 Andersonc2c79322009-07-28 18:32:17 +00002163 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002164 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2165 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002166 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002167 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002168 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002169 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002170 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002171 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002172 break;
2173 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002174 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002175 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2176 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002177 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002178
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002179 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002180 V = ConstantDataArray::getString(Context, Elts,
2181 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002182 break;
2183 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002184 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2185 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002186 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002187
Chris Lattner372dd1e2012-01-30 00:51:16 +00002188 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002189 if (EltTy->isIntegerTy(8)) {
2190 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2191 if (isa<VectorType>(CurTy))
2192 V = ConstantDataVector::get(Context, Elts);
2193 else
2194 V = ConstantDataArray::get(Context, Elts);
2195 } else if (EltTy->isIntegerTy(16)) {
2196 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2197 if (isa<VectorType>(CurTy))
2198 V = ConstantDataVector::get(Context, Elts);
2199 else
2200 V = ConstantDataArray::get(Context, Elts);
2201 } else if (EltTy->isIntegerTy(32)) {
2202 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2203 if (isa<VectorType>(CurTy))
2204 V = ConstantDataVector::get(Context, Elts);
2205 else
2206 V = ConstantDataArray::get(Context, Elts);
2207 } else if (EltTy->isIntegerTy(64)) {
2208 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2209 if (isa<VectorType>(CurTy))
2210 V = ConstantDataVector::get(Context, Elts);
2211 else
2212 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002213 } else if (EltTy->isHalfTy()) {
2214 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2215 if (isa<VectorType>(CurTy))
2216 V = ConstantDataVector::getFP(Context, Elts);
2217 else
2218 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002219 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002220 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002221 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002222 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002223 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002224 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002225 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002226 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002227 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002228 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002229 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002230 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002231 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002232 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002233 }
2234 break;
2235 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002236 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002237 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002238 return error("Invalid record");
2239 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002240 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002241 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002242 } else {
2243 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2244 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002245 unsigned Flags = 0;
2246 if (Record.size() >= 4) {
2247 if (Opc == Instruction::Add ||
2248 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002249 Opc == Instruction::Mul ||
2250 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002251 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2252 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2253 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2254 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002255 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002256 Opc == Instruction::UDiv ||
2257 Opc == Instruction::LShr ||
2258 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002259 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002260 Flags |= SDivOperator::IsExact;
2261 }
2262 }
2263 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002264 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002265 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002266 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002267 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002268 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002269 return error("Invalid record");
2270 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002271 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002272 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002273 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002274 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002275 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002276 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002277 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002278 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2279 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002280 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002281 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002282 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002283 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2284 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2285 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2286 // operands]
David Blaikieb9263572015-03-13 21:03:36 +00002287 unsigned OpNum = 0;
2288 Type *PointeeType = nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +00002289 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2290 Record.size() % 2)
David Blaikieb9263572015-03-13 21:03:36 +00002291 PointeeType = getTypeByID(Record[OpNum++]);
Peter Collingbourned93620b2016-11-10 22:34:55 +00002292
2293 bool InBounds = false;
2294 Optional<unsigned> InRangeIndex;
2295 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2296 uint64_t Op = Record[OpNum++];
2297 InBounds = Op & 1;
2298 InRangeIndex = Op >> 1;
2299 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2300 InBounds = true;
2301
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002302 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002303 while (OpNum != Record.size()) {
2304 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002305 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002306 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002307 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002308 }
David Blaikieb9263572015-03-13 21:03:36 +00002309
David Blaikieb9263572015-03-13 21:03:36 +00002310 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002311 PointeeType !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00002312 cast<PointerType>(Elts[0]->getType()->getScalarType())
David Blaikie4a2e73b2015-04-02 18:55:32 +00002313 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002314 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002315 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002316
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00002317 if (Elts.size() < 1)
2318 return error("Invalid gep with no operands");
2319
David Blaikie4a2e73b2015-04-02 18:55:32 +00002320 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2321 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002322 InBounds, InRangeIndex);
Chris Lattner890683d2007-04-24 18:15:21 +00002323 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002324 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002325 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002326 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002327 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002328
2329 Type *SelectorTy = Type::getInt1Ty(Context);
2330
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002331 // The selector might be an i1 or an <n x i1>
2332 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002333 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002334 if (Value *V = ValueList[Record[0]])
2335 if (SelectorTy != V->getType())
2336 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002337
2338 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2339 SelectorTy),
2340 ValueList.getConstantFwdRef(Record[1],CurTy),
2341 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002342 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002343 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002344 case bitc::CST_CODE_CE_EXTRACTELT
2345 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002346 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002347 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002348 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002349 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002350 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002351 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002352 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002353 Constant *Op1 = nullptr;
2354 if (Record.size() == 4) {
2355 Type *IdxTy = getTypeByID(Record[2]);
2356 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002357 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002358 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2359 } else // TODO: Remove with llvm 4.0
2360 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2361 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002362 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002363 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002364 break;
2365 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002366 case bitc::CST_CODE_CE_INSERTELT
2367 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002368 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002369 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002370 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002371 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2372 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2373 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002374 Constant *Op2 = nullptr;
2375 if (Record.size() == 4) {
2376 Type *IdxTy = getTypeByID(Record[2]);
2377 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002378 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002379 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2380 } else // TODO: Remove with llvm 4.0
2381 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2382 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002383 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002384 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002385 break;
2386 }
2387 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002388 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002389 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002390 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002391 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2392 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002393 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002394 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002395 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002396 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002397 break;
2398 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002399 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002400 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2401 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002402 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002403 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002404 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002405 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2406 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002407 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002408 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002409 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002410 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002411 break;
2412 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002413 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002414 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002415 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002416 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002417 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002418 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002419 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2420 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2421
Duncan Sands9dff9be2010-02-15 16:12:20 +00002422 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002423 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002424 else
Owen Anderson487375e2009-07-29 18:55:55 +00002425 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002426 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002427 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002428 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002429 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002430 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002431 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002432 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002433 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002434 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002435 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002436 unsigned AsmStrSize = Record[1];
2437 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002438 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002439 unsigned ConstStrSize = Record[2+AsmStrSize];
2440 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002441 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002442
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002443 for (unsigned i = 0; i != AsmStrSize; ++i)
2444 AsmStr += (char)Record[2+i];
2445 for (unsigned i = 0; i != ConstStrSize; ++i)
2446 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002447 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002448 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002449 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002450 break;
2451 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002452 // This version adds support for the asm dialect keywords (e.g.,
2453 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002454 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002455 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002456 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002457 std::string AsmStr, ConstrStr;
2458 bool HasSideEffects = Record[0] & 1;
2459 bool IsAlignStack = (Record[0] >> 1) & 1;
2460 unsigned AsmDialect = Record[0] >> 2;
2461 unsigned AsmStrSize = Record[1];
2462 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002463 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002464 unsigned ConstStrSize = Record[2+AsmStrSize];
2465 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002466 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002467
2468 for (unsigned i = 0; i != AsmStrSize; ++i)
2469 AsmStr += (char)Record[2+i];
2470 for (unsigned i = 0; i != ConstStrSize; ++i)
2471 ConstrStr += (char)Record[3+AsmStrSize+i];
2472 PointerType *PTy = cast<PointerType>(CurTy);
2473 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2474 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002475 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002476 break;
2477 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002478 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002479 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002480 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002481 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002482 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002483 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002484 Function *Fn =
2485 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002486 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002487 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002488
2489 // If the function is already parsed we can insert the block address right
2490 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002491 BasicBlock *BB;
2492 unsigned BBID = Record[2];
2493 if (!BBID)
2494 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002495 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002496 if (!Fn->empty()) {
2497 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002498 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002499 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002500 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002501 ++BBI;
2502 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00002503 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002504 } else {
2505 // Otherwise insert a placeholder and remember it so it can be inserted
2506 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002507 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2508 if (FwdBBs.empty())
2509 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002510 if (FwdBBs.size() < BBID + 1)
2511 FwdBBs.resize(BBID + 1);
2512 if (!FwdBBs[BBID])
2513 FwdBBs[BBID] = BasicBlock::Create(Context);
2514 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002515 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002516 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002517 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002518 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002519 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002520
David Majnemer8a1c45d2015-12-12 05:38:55 +00002521 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002522 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002523 }
2524}
Chris Lattner1314b992007-04-22 06:23:29 +00002525
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002526Error BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002527 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002528 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002529
Chad Rosierca2567b2011-12-07 21:44:12 +00002530 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002531 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00002532
2533 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002534 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002535
Chris Lattner27d38752013-01-20 02:13:19 +00002536 switch (Entry.Kind) {
2537 case BitstreamEntry::SubBlock: // Handled for us already.
2538 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002539 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002540 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002541 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002542 case BitstreamEntry::Record:
2543 // The interesting case.
2544 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002545 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002546
Chad Rosierca2567b2011-12-07 21:44:12 +00002547 // Read a use list record.
2548 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002549 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002550 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002551 default: // Default behavior: unknown type.
2552 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002553 case bitc::USELIST_CODE_BB:
2554 IsBB = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00002555 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002556 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002557 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002558 if (RecordLength < 3)
2559 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002560 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002561 unsigned ID = Record.back();
2562 Record.pop_back();
2563
2564 Value *V;
2565 if (IsBB) {
2566 assert(ID < FunctionBBs.size() && "Basic block not found");
2567 V = FunctionBBs[ID];
2568 } else
2569 V = ValueList[ID];
2570 unsigned NumUses = 0;
2571 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00002572 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002573 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002574 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002575 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002576 }
2577 if (Order.size() != Record.size() || NumUses > Record.size())
2578 // Mismatches can happen if the functions are being materialized lazily
2579 // (out-of-order), or a value has been upgraded.
2580 break;
2581
2582 V->sortUseList([&](const Use &L, const Use &R) {
2583 return Order.lookup(&L) < Order.lookup(&R);
2584 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002585 break;
2586 }
2587 }
2588 }
2589}
2590
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002591/// When we see the block for metadata, remember where it is and then skip it.
2592/// This lets us lazily deserialize the metadata.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002593Error BitcodeReader::rememberAndSkipMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002594 // Save the current stream state.
2595 uint64_t CurBit = Stream.GetCurrentBitNo();
2596 DeferredMetadataInfo.push_back(CurBit);
2597
2598 // Skip over the block for now.
2599 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002600 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002601 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002602}
2603
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00002604Error BitcodeReader::materializeMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002605 for (uint64_t BitPos : DeferredMetadataInfo) {
2606 // Move the bit stream to the saved position.
2607 Stream.JumpToBit(BitPos);
Mehdi Aminief27db82016-12-12 19:34:26 +00002608 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002609 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002610 }
Peter Collingbourne89061b22017-06-12 20:10:48 +00002611
2612 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2613 // metadata.
2614 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2615 NamedMDNode *LinkerOpts =
2616 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2617 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2618 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2619 }
2620
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002621 DeferredMetadataInfo.clear();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002622 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002623}
2624
Rafael Espindola468b8682015-04-01 14:44:59 +00002625void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002626
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002627/// When we see the block for a function body, remember where it is and then
2628/// skip it. This lets us lazily deserialize the functions.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002629Error BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002630 // Get the function we are talking about.
2631 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002632 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002633
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002634 Function *Fn = FunctionsWithBodies.back();
2635 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002637 // Save the current stream state.
2638 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00002639 assert(
2640 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2641 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002642 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002643
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002644 // Skip over the function block for now.
2645 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002646 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002647 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002648}
2649
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002650Error BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002651 // Patch the initializers for globals and aliases up.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002652 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2653 return Err;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002654 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002655 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002656
2657 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002658 for (Function &F : *TheModule) {
Adrian Prantl6825fb62017-04-18 01:21:53 +00002659 MDLoader->upgradeDebugIntrinsics(F);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002660 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002661 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00002662 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00002663 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2664 // Some types could be renamed during loading if several modules are
2665 // loaded in the same LLVMContext (LTO scenario). In this case we should
2666 // remangle intrinsics names as well.
2667 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002668 }
2669
2670 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002671 for (GlobalVariable &GV : TheModule->globals())
2672 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002673
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002674 // Force deallocation of memory for these vectors to favor the client that
2675 // want lazy deserialization.
2676 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002677 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
2678 IndirectSymbolInits);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002679 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002680}
2681
Teresa Johnson1493ad92015-10-10 14:18:36 +00002682/// Support for lazy parsing of function bodies. This is required if we
2683/// either have an old bitcode file without a VST forward declaration record,
2684/// or if we have an anonymous function being materialized, since anonymous
2685/// functions do not have a name and are therefore not in the VST.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002686Error BitcodeReader::rememberAndSkipFunctionBodies() {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002687 Stream.JumpToBit(NextUnreadBit);
2688
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002689 if (Stream.AtEndOfStream())
2690 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00002691
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00002692 if (!SeenFirstFunctionBody)
2693 return error("Trying to materialize functions before seeing function blocks");
2694
Teresa Johnson1493ad92015-10-10 14:18:36 +00002695 // An old bitcode file with the symbol table at the end would have
2696 // finished the parse greedily.
2697 assert(SeenValueSymbolTable);
2698
2699 SmallVector<uint64_t, 64> Record;
2700
Eugene Zelenko1804a772016-08-25 00:45:04 +00002701 while (true) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002702 BitstreamEntry Entry = Stream.advance();
2703 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002704 default:
2705 return error("Expect SubBlock");
2706 case BitstreamEntry::SubBlock:
2707 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002708 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002709 return error("Expect function block");
2710 case bitc::FUNCTION_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002711 if (Error Err = rememberAndSkipFunctionBody())
2712 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002713 NextUnreadBit = Stream.GetCurrentBitNo();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002714 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002715 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00002716 }
2717 }
2718}
2719
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002720bool BitcodeReaderBase::readBlockInfo() {
Peter Collingbourne77c89b62016-11-08 04:17:11 +00002721 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2722 if (!NewBlockInfo)
2723 return true;
2724 BlockInfo = std::move(*NewBlockInfo);
2725 return false;
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002726}
2727
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002728Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002729 // v1: [selection_kind, name]
2730 // v2: [strtab_offset, strtab_size, selection_kind]
2731 StringRef Name;
2732 std::tie(Name, Record) = readNameFromStrtab(Record);
2733
2734 if (Record.size() < 1)
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002735 return error("Invalid record");
2736 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002737 std::string OldFormatName;
2738 if (!UseStrtab) {
2739 if (Record.size() < 2)
2740 return error("Invalid record");
2741 unsigned ComdatNameSize = Record[1];
2742 OldFormatName.reserve(ComdatNameSize);
2743 for (unsigned i = 0; i != ComdatNameSize; ++i)
2744 OldFormatName += (char)Record[2 + i];
2745 Name = OldFormatName;
2746 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002747 Comdat *C = TheModule->getOrInsertComdat(Name);
2748 C->setSelectionKind(SK);
2749 ComdatList.push_back(C);
2750 return Error::success();
2751}
2752
2753Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002754 // v1: [pointer type, isconst, initid, linkage, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002755 // visibility, threadlocal, unnamed_addr, externally_initialized,
Javed Absarf3d79042017-05-11 12:28:08 +00002756 // dllstorageclass, comdat, attributes] (name in VST)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002757 // v2: [strtab_offset, strtab_size, v1]
2758 StringRef Name;
2759 std::tie(Name, Record) = readNameFromStrtab(Record);
2760
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002761 if (Record.size() < 6)
2762 return error("Invalid record");
2763 Type *Ty = getTypeByID(Record[0]);
2764 if (!Ty)
2765 return error("Invalid record");
2766 bool isConstant = Record[1] & 1;
2767 bool explicitType = Record[1] & 2;
2768 unsigned AddressSpace;
2769 if (explicitType) {
2770 AddressSpace = Record[1] >> 2;
2771 } else {
2772 if (!Ty->isPointerTy())
2773 return error("Invalid type for value");
2774 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2775 Ty = cast<PointerType>(Ty)->getElementType();
2776 }
2777
2778 uint64_t RawLinkage = Record[3];
2779 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2780 unsigned Alignment;
2781 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2782 return Err;
2783 std::string Section;
2784 if (Record[5]) {
2785 if (Record[5] - 1 >= SectionTable.size())
2786 return error("Invalid ID");
2787 Section = SectionTable[Record[5] - 1];
2788 }
2789 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2790 // Local linkage must have default visibility.
2791 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2792 // FIXME: Change to an error if non-default in 4.0.
2793 Visibility = getDecodedVisibility(Record[6]);
2794
2795 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2796 if (Record.size() > 7)
2797 TLM = getDecodedThreadLocalMode(Record[7]);
2798
2799 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2800 if (Record.size() > 8)
2801 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2802
2803 bool ExternallyInitialized = false;
2804 if (Record.size() > 9)
2805 ExternallyInitialized = Record[9];
2806
2807 GlobalVariable *NewGV =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002808 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002809 nullptr, TLM, AddressSpace, ExternallyInitialized);
2810 NewGV->setAlignment(Alignment);
2811 if (!Section.empty())
2812 NewGV->setSection(Section);
2813 NewGV->setVisibility(Visibility);
2814 NewGV->setUnnamedAddr(UnnamedAddr);
2815
2816 if (Record.size() > 10)
2817 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2818 else
2819 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2820
2821 ValueList.push_back(NewGV);
2822
2823 // Remember which value to use for the global initializer.
2824 if (unsigned InitID = Record[2])
2825 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2826
2827 if (Record.size() > 11) {
2828 if (unsigned ComdatID = Record[11]) {
2829 if (ComdatID > ComdatList.size())
2830 return error("Invalid global variable comdat ID");
2831 NewGV->setComdat(ComdatList[ComdatID - 1]);
2832 }
2833 } else if (hasImplicitComdat(RawLinkage)) {
2834 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2835 }
Javed Absarf3d79042017-05-11 12:28:08 +00002836
2837 if (Record.size() > 12) {
2838 auto AS = getAttributes(Record[12]).getFnAttributes();
2839 NewGV->setAttributes(AS);
2840 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002841 return Error::success();
2842}
2843
2844Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002845 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002846 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002847 // prefixdata] (name in VST)
2848 // v2: [strtab_offset, strtab_size, v1]
2849 StringRef Name;
2850 std::tie(Name, Record) = readNameFromStrtab(Record);
2851
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002852 if (Record.size() < 8)
2853 return error("Invalid record");
2854 Type *Ty = getTypeByID(Record[0]);
2855 if (!Ty)
2856 return error("Invalid record");
2857 if (auto *PTy = dyn_cast<PointerType>(Ty))
2858 Ty = PTy->getElementType();
2859 auto *FTy = dyn_cast<FunctionType>(Ty);
2860 if (!FTy)
2861 return error("Invalid type for value");
2862 auto CC = static_cast<CallingConv::ID>(Record[1]);
2863 if (CC & ~CallingConv::MaxID)
2864 return error("Invalid calling convention ID");
2865
2866 Function *Func =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002867 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002868
2869 Func->setCallingConv(CC);
2870 bool isProto = Record[2];
2871 uint64_t RawLinkage = Record[3];
2872 Func->setLinkage(getDecodedLinkage(RawLinkage));
2873 Func->setAttributes(getAttributes(Record[4]));
2874
2875 unsigned Alignment;
2876 if (Error Err = parseAlignmentValue(Record[5], Alignment))
2877 return Err;
2878 Func->setAlignment(Alignment);
2879 if (Record[6]) {
2880 if (Record[6] - 1 >= SectionTable.size())
2881 return error("Invalid ID");
2882 Func->setSection(SectionTable[Record[6] - 1]);
2883 }
2884 // Local linkage must have default visibility.
2885 if (!Func->hasLocalLinkage())
2886 // FIXME: Change to an error if non-default in 4.0.
2887 Func->setVisibility(getDecodedVisibility(Record[7]));
2888 if (Record.size() > 8 && Record[8]) {
2889 if (Record[8] - 1 >= GCTable.size())
2890 return error("Invalid ID");
2891 Func->setGC(GCTable[Record[8] - 1]);
2892 }
2893 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2894 if (Record.size() > 9)
2895 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2896 Func->setUnnamedAddr(UnnamedAddr);
2897 if (Record.size() > 10 && Record[10] != 0)
2898 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2899
2900 if (Record.size() > 11)
2901 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2902 else
2903 upgradeDLLImportExportLinkage(Func, RawLinkage);
2904
2905 if (Record.size() > 12) {
2906 if (unsigned ComdatID = Record[12]) {
2907 if (ComdatID > ComdatList.size())
2908 return error("Invalid function comdat ID");
2909 Func->setComdat(ComdatList[ComdatID - 1]);
2910 }
2911 } else if (hasImplicitComdat(RawLinkage)) {
2912 Func->setComdat(reinterpret_cast<Comdat *>(1));
2913 }
2914
2915 if (Record.size() > 13 && Record[13] != 0)
2916 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2917
2918 if (Record.size() > 14 && Record[14] != 0)
2919 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2920
2921 ValueList.push_back(Func);
2922
2923 // If this is a function with a body, remember the prototype we are
2924 // creating now, so that we can match up the body with them later.
2925 if (!isProto) {
2926 Func->setIsMaterializable(true);
2927 FunctionsWithBodies.push_back(Func);
2928 DeferredFunctionInfo[Func] = 0;
2929 }
2930 return Error::success();
2931}
2932
2933Error BitcodeReader::parseGlobalIndirectSymbolRecord(
2934 unsigned BitCode, ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002935 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
2936 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
2937 // dllstorageclass] (name in VST)
2938 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
2939 // visibility, dllstorageclass] (name in VST)
2940 // v2: [strtab_offset, strtab_size, v1]
2941 StringRef Name;
2942 std::tie(Name, Record) = readNameFromStrtab(Record);
2943
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002944 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
2945 if (Record.size() < (3 + (unsigned)NewRecord))
2946 return error("Invalid record");
2947 unsigned OpNum = 0;
2948 Type *Ty = getTypeByID(Record[OpNum++]);
2949 if (!Ty)
2950 return error("Invalid record");
2951
2952 unsigned AddrSpace;
2953 if (!NewRecord) {
2954 auto *PTy = dyn_cast<PointerType>(Ty);
2955 if (!PTy)
2956 return error("Invalid type for value");
2957 Ty = PTy->getElementType();
2958 AddrSpace = PTy->getAddressSpace();
2959 } else {
2960 AddrSpace = Record[OpNum++];
2961 }
2962
2963 auto Val = Record[OpNum++];
2964 auto Linkage = Record[OpNum++];
2965 GlobalIndirectSymbol *NewGA;
2966 if (BitCode == bitc::MODULE_CODE_ALIAS ||
2967 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002968 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002969 TheModule);
2970 else
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002971 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002972 nullptr, TheModule);
2973 // Old bitcode files didn't have visibility field.
2974 // Local linkage must have default visibility.
2975 if (OpNum != Record.size()) {
2976 auto VisInd = OpNum++;
2977 if (!NewGA->hasLocalLinkage())
2978 // FIXME: Change to an error if non-default in 4.0.
2979 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
2980 }
2981 if (OpNum != Record.size())
2982 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
2983 else
2984 upgradeDLLImportExportLinkage(NewGA, Linkage);
2985 if (OpNum != Record.size())
2986 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
2987 if (OpNum != Record.size())
2988 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
2989 ValueList.push_back(NewGA);
2990 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
2991 return Error::success();
2992}
2993
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002994Error BitcodeReader::parseModule(uint64_t ResumeBit,
2995 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002996 if (ResumeBit)
2997 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002998 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002999 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003000
Chris Lattner1314b992007-04-22 06:23:29 +00003001 SmallVector<uint64_t, 64> Record;
Chris Lattner1314b992007-04-22 06:23:29 +00003002
3003 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00003004 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003005 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003006
Chris Lattner27d38752013-01-20 02:13:19 +00003007 switch (Entry.Kind) {
3008 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003009 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003010 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003011 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003012
Chris Lattner27d38752013-01-20 02:13:19 +00003013 case BitstreamEntry::SubBlock:
3014 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003015 default: // Skip unknown content.
3016 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003017 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003018 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003019 case bitc::BLOCKINFO_BLOCK_ID:
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003020 if (readBlockInfo())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003021 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003022 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003023 case bitc::PARAMATTR_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003024 if (Error Err = parseAttributeBlock())
3025 return Err;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003026 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003027 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003028 if (Error Err = parseAttributeGroupBlock())
3029 return Err;
Bill Wendlingba629332013-02-10 23:24:25 +00003030 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003031 case bitc::TYPE_BLOCK_ID_NEW:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003032 if (Error Err = parseTypeTable())
3033 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003034 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003035 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003036 if (!SeenValueSymbolTable) {
3037 // Either this is an old form VST without function index and an
3038 // associated VST forward declaration record (which would have caused
3039 // the VST to be jumped to and parsed before it was encountered
3040 // normally in the stream), or there were no function blocks to
3041 // trigger an earlier parsing of the VST.
3042 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003043 if (Error Err = parseValueSymbolTable())
3044 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003045 SeenValueSymbolTable = true;
3046 } else {
3047 // We must have had a VST forward declaration record, which caused
3048 // the parser to jump to and parse the VST earlier.
3049 assert(VSTOffset > 0);
3050 if (Stream.SkipBlock())
3051 return error("Invalid record");
3052 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003053 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003054 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003055 if (Error Err = parseConstants())
3056 return Err;
3057 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3058 return Err;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003059 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003060 case bitc::METADATA_BLOCK_ID:
Mehdi Aminibf2090e2016-12-12 19:23:39 +00003061 if (ShouldLazyLoadMetadata) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003062 if (Error Err = rememberAndSkipMetadata())
3063 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003064 break;
3065 }
3066 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Mehdi Aminief27db82016-12-12 19:34:26 +00003067 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003068 return Err;
Devang Patel7428d8a2009-07-22 17:43:22 +00003069 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003070 case bitc::METADATA_KIND_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003071 if (Error Err = MDLoader->parseMetadataKinds())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003072 return Err;
Teresa Johnson12545072015-11-15 02:00:09 +00003073 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003074 case bitc::FUNCTION_BLOCK_ID:
Mehdi Amini466a64e2016-08-13 23:39:14 +00003075 // If this is the first function body we've seen, reverse the
3076 // FunctionsWithBodies list.
3077 if (!SeenFirstFunctionBody) {
3078 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003079 if (Error Err = globalCleanup())
3080 return Err;
Mehdi Amini466a64e2016-08-13 23:39:14 +00003081 SeenFirstFunctionBody = true;
3082 }
3083
Teresa Johnsonff642b92015-09-17 20:12:00 +00003084 if (VSTOffset > 0) {
3085 // If we have a VST forward declaration record, make sure we
3086 // parse the VST now if we haven't already. It is needed to
3087 // set up the DeferredFunctionInfo vector for lazy reading.
3088 if (!SeenValueSymbolTable) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003089 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3090 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003091 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003092 // Fall through so that we record the NextUnreadBit below.
3093 // This is necessary in case we have an anonymous function that
3094 // is later materialized. Since it will not have a VST entry we
3095 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003096 } else {
3097 // If we have a VST forward declaration record, but have already
3098 // parsed the VST (just above, when the first function body was
3099 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003100 // materializing functions. The ResumeBit points to the
3101 // start of the last function block recorded in the
3102 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003103 if (Stream.SkipBlock())
3104 return error("Invalid record");
3105 continue;
3106 }
3107 }
3108
3109 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003110 // index in the VST, nor a VST forward declaration record, as
3111 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003112 // Build the DeferredFunctionInfo vector on the fly.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003113 if (Error Err = rememberAndSkipFunctionBody())
3114 return Err;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003115
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003116 // Suspend parsing when we reach the function bodies. Subsequent
3117 // materialization calls will resume it when necessary. If the bitcode
3118 // file is old, the symbol table will be at the end instead and will not
3119 // have been seen yet. In this case, just finish the parse now.
3120 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003121 NextUnreadBit = Stream.GetCurrentBitNo();
Mehdi Aminia71002e2016-08-14 00:01:27 +00003122 // After the VST has been parsed, we need to make sure intrinsic name
3123 // are auto-upgraded.
3124 return globalCleanup();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003125 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003126 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003127 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003128 if (Error Err = parseUseLists())
3129 return Err;
Chad Rosierca2567b2011-12-07 21:44:12 +00003130 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003131 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003132 if (Error Err = parseOperandBundleTags())
3133 return Err;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003134 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003135 }
3136 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003137
Chris Lattner27d38752013-01-20 02:13:19 +00003138 case BitstreamEntry::Record:
3139 // The interesting case.
3140 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003141 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003142
Chris Lattner1314b992007-04-22 06:23:29 +00003143 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003144 auto BitCode = Stream.readRecord(Entry.ID, Record);
3145 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003146 default: break; // Default behavior, ignore unknown content.
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003147 case bitc::MODULE_CODE_VERSION: {
3148 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3149 if (!VersionOrErr)
3150 return VersionOrErr.takeError();
3151 UseRelativeIDs = *VersionOrErr >= 1;
Chris Lattner1314b992007-04-22 06:23:29 +00003152 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003153 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003154 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003155 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003156 if (convertToString(Record, 0, S))
3157 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003158 TheModule->setTargetTriple(S);
3159 break;
3160 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003161 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003162 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003163 if (convertToString(Record, 0, S))
3164 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003165 TheModule->setDataLayout(S);
3166 break;
3167 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003168 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003169 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003170 if (convertToString(Record, 0, S))
3171 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003172 TheModule->setModuleInlineAsm(S);
3173 break;
3174 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003175 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3176 // FIXME: Remove in 4.0.
3177 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003178 if (convertToString(Record, 0, S))
3179 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003180 // Ignore value.
3181 break;
3182 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003183 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003184 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003185 if (convertToString(Record, 0, S))
3186 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003187 SectionTable.push_back(S);
3188 break;
3189 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003190 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003191 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003192 if (convertToString(Record, 0, S))
3193 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003194 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003195 break;
3196 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003197 case bitc::MODULE_CODE_COMDAT: {
3198 if (Error Err = parseComdatRecord(Record))
3199 return Err;
David Majnemerdad0a642014-06-27 18:19:56 +00003200 break;
3201 }
Chris Lattner1314b992007-04-22 06:23:29 +00003202 case bitc::MODULE_CODE_GLOBALVAR: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003203 if (Error Err = parseGlobalVarRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003204 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003205 break;
3206 }
Chris Lattner1314b992007-04-22 06:23:29 +00003207 case bitc::MODULE_CODE_FUNCTION: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003208 if (Error Err = parseFunctionRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003209 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003210 break;
3211 }
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003212 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003213 case bitc::MODULE_CODE_ALIAS:
3214 case bitc::MODULE_CODE_ALIAS_OLD: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003215 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3216 return Err;
Chris Lattner44c17072007-04-26 02:46:40 +00003217 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003218 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00003219 /// MODULE_CODE_VSTOFFSET: [offset]
3220 case bitc::MODULE_CODE_VSTOFFSET:
3221 if (Record.size() < 1)
3222 return error("Invalid record");
Peter Collingbournebfcf9802016-11-29 02:27:04 +00003223 // Note that we subtract 1 here because the offset is relative to one word
3224 // before the start of the identification or module block, which was
3225 // historically always the start of the regular bitcode header.
3226 VSTOffset = Record[0] - 1;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003227 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003228 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3229 case bitc::MODULE_CODE_SOURCE_FILENAME:
3230 SmallString<128> ValueName;
3231 if (convertToString(Record, 0, ValueName))
3232 return error("Invalid record");
3233 TheModule->setSourceFileName(ValueName);
3234 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003235 }
Chris Lattner1314b992007-04-22 06:23:29 +00003236 Record.clear();
3237 }
Chris Lattner1314b992007-04-22 06:23:29 +00003238}
3239
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003240Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3241 bool IsImporting) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003242 TheModule = M;
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003243 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00003244 [&](unsigned ID) { return getTypeByID(ID); });
Peter Collingbourne7a748032016-11-16 21:44:45 +00003245 return parseModule(0, ShouldLazyLoadMetadata);
Chris Lattner1314b992007-04-22 06:23:29 +00003246}
Chris Lattner6694f602007-04-29 07:54:31 +00003247
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003248
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003249Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003250 if (!isa<PointerType>(PtrType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003251 return error("Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003252 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3253
3254 if (ValType && ValType != ElemType)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003255 return error("Explicit load/store type does not match pointee "
3256 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003257 if (!PointerType::isLoadableOrStorableType(ElemType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003258 return error("Cannot load/store from pointer");
3259 return Error::success();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003260}
3261
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003262/// Lazily parse the specified function body block.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003263Error BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003264 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003265 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003266
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003267 // Unexpected unresolved metadata when parsing function.
Mehdi Aminief27db82016-12-12 19:34:26 +00003268 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003269 return error("Invalid function metadata: incoming forward references");
3270
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003271 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003272 unsigned ModuleValueListSize = ValueList.size();
Mehdi Aminief27db82016-12-12 19:34:26 +00003273 unsigned ModuleMDLoaderSize = MDLoader->size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003274
Chris Lattner85b7b402007-05-01 05:52:21 +00003275 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003276 for (Argument &I : F->args())
3277 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003278
Chris Lattner83930552007-05-01 07:01:57 +00003279 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003280 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003281 unsigned CurBBNo = 0;
3282
Chris Lattner07d09ed2010-04-03 02:17:50 +00003283 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003284 auto getLastInstruction = [&]() -> Instruction * {
3285 if (CurBB && !CurBB->empty())
3286 return &CurBB->back();
3287 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3288 !FunctionBBs[CurBBNo - 1]->empty())
3289 return &FunctionBBs[CurBBNo - 1]->back();
3290 return nullptr;
3291 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003292
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003293 std::vector<OperandBundleDef> OperandBundles;
3294
Chris Lattner85b7b402007-05-01 05:52:21 +00003295 // Read all the records.
3296 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00003297
3298 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003299 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003300
Chris Lattner27d38752013-01-20 02:13:19 +00003301 switch (Entry.Kind) {
3302 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003303 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003304 case BitstreamEntry::EndBlock:
3305 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003306
Chris Lattner27d38752013-01-20 02:13:19 +00003307 case BitstreamEntry::SubBlock:
3308 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003309 default: // Skip unknown content.
3310 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003311 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003312 break;
3313 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003314 if (Error Err = parseConstants())
3315 return Err;
Chris Lattner83930552007-05-01 07:01:57 +00003316 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003317 break;
3318 case bitc::VALUE_SYMTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003319 if (Error Err = parseValueSymbolTable())
3320 return Err;
Chris Lattner85b7b402007-05-01 05:52:21 +00003321 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003322 case bitc::METADATA_ATTACHMENT_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003323 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003324 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003325 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003326 case bitc::METADATA_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003327 assert(DeferredMetadataInfo.empty() &&
3328 "Must read all module-level metadata before function-level");
3329 if (Error Err = MDLoader->parseFunctionMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003330 return Err;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003331 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003332 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003333 if (Error Err = parseUseLists())
3334 return Err;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003335 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003336 }
3337 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003338
Chris Lattner27d38752013-01-20 02:13:19 +00003339 case BitstreamEntry::Record:
3340 // The interesting case.
3341 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003342 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003343
Chris Lattner85b7b402007-05-01 05:52:21 +00003344 // Read a record.
3345 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003346 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003347 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003348 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003349 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003350 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003351 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003352 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003353 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003354 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003355 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003356
3357 // See if anything took the address of blocks in this function.
3358 auto BBFRI = BasicBlockFwdRefs.find(F);
3359 if (BBFRI == BasicBlockFwdRefs.end()) {
3360 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3361 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3362 } else {
3363 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003364 // Check for invalid basic block references.
3365 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003366 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003367 assert(!BBRefs.empty() && "Unexpected empty array");
3368 assert(!BBRefs.front() && "Invalid reference to entry block");
3369 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3370 ++I)
3371 if (I < RE && BBRefs[I]) {
3372 BBRefs[I]->insertInto(F);
3373 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003374 } else {
3375 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3376 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003377
3378 // Erase from the table.
3379 BasicBlockFwdRefs.erase(BBFRI);
3380 }
3381
Chris Lattner83930552007-05-01 07:01:57 +00003382 CurBB = FunctionBBs[0];
3383 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003384 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003385
Chris Lattner07d09ed2010-04-03 02:17:50 +00003386 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3387 // This record indicates that the last instruction is at the same
3388 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003389 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003390
Craig Topper2617dcc2014-04-15 06:32:26 +00003391 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003392 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003393 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003394 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003395 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003396
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003397 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003398 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003399 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003400 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003401
Chris Lattner07d09ed2010-04-03 02:17:50 +00003402 unsigned Line = Record[0], Col = Record[1];
3403 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003404
Craig Topper2617dcc2014-04-15 06:32:26 +00003405 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00003406 if (ScopeID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003407 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003408 if (!Scope)
3409 return error("Invalid record");
3410 }
3411 if (IAID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003412 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003413 if (!IA)
3414 return error("Invalid record");
3415 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00003416 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3417 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003418 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003419 continue;
3420 }
3421
Chris Lattnere9759c22007-05-06 00:21:25 +00003422 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3423 unsigned OpNum = 0;
3424 Value *LHS, *RHS;
3425 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003426 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003427 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003428 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003429
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003430 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003431 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003432 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003433 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003434 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003435 if (OpNum < Record.size()) {
3436 if (Opc == Instruction::Add ||
3437 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003438 Opc == Instruction::Mul ||
3439 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003440 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003441 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003442 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003443 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003444 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003445 Opc == Instruction::UDiv ||
3446 Opc == Instruction::LShr ||
3447 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003448 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003449 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003450 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00003451 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003452 if (FMF.any())
3453 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003454 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003455
Dan Gohman1b849082009-09-07 23:54:19 +00003456 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003457 break;
3458 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003459 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3460 unsigned OpNum = 0;
3461 Value *Op;
3462 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3463 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003464 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003465
Chris Lattner229907c2011-07-18 04:54:35 +00003466 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003467 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003468 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003469 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003470 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003471 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3472 if (Temp) {
3473 InstructionList.push_back(Temp);
3474 CurBB->getInstList().push_back(Temp);
3475 }
3476 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00003477 auto CastOp = (Instruction::CastOps)Opc;
3478 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3479 return error("Invalid cast");
3480 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003481 }
Devang Patelaf206b82009-09-18 19:26:43 +00003482 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003483 break;
3484 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003485 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3486 case bitc::FUNC_CODE_INST_GEP_OLD:
3487 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003488 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003489
3490 Type *Ty;
3491 bool InBounds;
3492
3493 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3494 InBounds = Record[OpNum++];
3495 Ty = getTypeByID(Record[OpNum++]);
3496 } else {
3497 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3498 Ty = nullptr;
3499 }
3500
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003501 Value *BasePtr;
3502 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003503 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003504
David Blaikie60310f22015-05-08 00:42:26 +00003505 if (!Ty)
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003506 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003507 ->getElementType();
3508 else if (Ty !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003509 cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003510 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003511 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00003512 "Explicit gep type does not match pointee type of pointer operand");
3513
Chris Lattner5285b5e2007-05-02 05:46:45 +00003514 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003515 while (OpNum != Record.size()) {
3516 Value *Op;
3517 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003518 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003519 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003520 }
3521
David Blaikie096b1da2015-03-14 19:53:33 +00003522 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003523
Devang Patelaf206b82009-09-18 19:26:43 +00003524 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003525 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003526 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003527 break;
3528 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003529
Dan Gohman1ecaf452008-05-31 00:58:22 +00003530 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3531 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003532 unsigned OpNum = 0;
3533 Value *Agg;
3534 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003535 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003536
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003537 unsigned RecSize = Record.size();
3538 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003539 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003540
Dan Gohman1ecaf452008-05-31 00:58:22 +00003541 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003542 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003543 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003544 bool IsArray = CurTy->isArrayTy();
3545 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003546 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003547
3548 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003549 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003550 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003551 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003552 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003553 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003554 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003555 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003556 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003557
3558 if (IsStruct)
3559 CurTy = CurTy->subtypes()[Index];
3560 else
3561 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003562 }
3563
Jay Foad57aa6362011-07-13 10:26:04 +00003564 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003565 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003566 break;
3567 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003568
Dan Gohman1ecaf452008-05-31 00:58:22 +00003569 case bitc::FUNC_CODE_INST_INSERTVAL: {
3570 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003571 unsigned OpNum = 0;
3572 Value *Agg;
3573 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003574 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003575 Value *Val;
3576 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003577 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003578
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003579 unsigned RecSize = Record.size();
3580 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003581 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003582
Dan Gohman1ecaf452008-05-31 00:58:22 +00003583 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003584 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003585 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003586 bool IsArray = CurTy->isArrayTy();
3587 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003588 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003589
3590 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003591 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003592 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003593 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003594 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003595 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003596 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003597 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003598
Dan Gohman1ecaf452008-05-31 00:58:22 +00003599 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003600 if (IsStruct)
3601 CurTy = CurTy->subtypes()[Index];
3602 else
3603 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003604 }
3605
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003606 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003607 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003608
Jay Foad57aa6362011-07-13 10:26:04 +00003609 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003610 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003611 break;
3612 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003613
Chris Lattnere9759c22007-05-06 00:21:25 +00003614 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003615 // obsolete form of select
3616 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003617 unsigned OpNum = 0;
3618 Value *TrueVal, *FalseVal, *Cond;
3619 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003620 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3621 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003622 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003623
Dan Gohmanc5d28922008-09-16 01:01:33 +00003624 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003625 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003626 break;
3627 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003628
Dan Gohmanc5d28922008-09-16 01:01:33 +00003629 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3630 // new form of select
3631 // handles select i1 or select [N x i1]
3632 unsigned OpNum = 0;
3633 Value *TrueVal, *FalseVal, *Cond;
3634 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003635 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003636 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003637 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003638
3639 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003640 if (VectorType* vector_type =
3641 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003642 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003643 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003644 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003645 } else {
3646 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003647 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003648 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003649 }
3650
Gabor Greife9ecc682008-04-06 20:25:17 +00003651 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003652 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003653 break;
3654 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003655
Chris Lattner1fc27f02007-05-02 05:16:49 +00003656 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003657 unsigned OpNum = 0;
3658 Value *Vec, *Idx;
3659 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003660 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003661 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003662 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003663 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003664 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003665 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003666 break;
3667 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003668
Chris Lattner1fc27f02007-05-02 05:16:49 +00003669 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003670 unsigned OpNum = 0;
3671 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003672 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003673 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003674 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003675 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003676 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003677 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003678 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003679 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003680 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003681 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003682 break;
3683 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003684
Chris Lattnere9759c22007-05-06 00:21:25 +00003685 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3686 unsigned OpNum = 0;
3687 Value *Vec1, *Vec2, *Mask;
3688 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003689 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003690 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003691
Mon P Wang25f01062008-11-10 04:46:22 +00003692 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003693 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003694 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003695 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003696 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003697 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003698 break;
3699 }
Mon P Wang25f01062008-11-10 04:46:22 +00003700
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003701 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3702 // Old form of ICmp/FCmp returning bool
3703 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3704 // both legal on vectors but had different behaviour.
3705 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3706 // FCmp/ICmp returning bool or vector of bool
3707
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003708 unsigned OpNum = 0;
3709 Value *LHS, *RHS;
3710 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00003711 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3712 return error("Invalid record");
3713
3714 unsigned PredVal = Record[OpNum];
3715 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3716 FastMathFlags FMF;
3717 if (IsFP && Record.size() > OpNum+1)
3718 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3719
3720 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003721 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003722
Duncan Sands9dff9be2010-02-15 16:12:20 +00003723 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00003724 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003725 else
James Molloy88eb5352015-07-10 12:52:00 +00003726 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3727
3728 if (FMF.any())
3729 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00003730 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003731 break;
3732 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003733
Chris Lattnere53603e2007-05-02 04:27:25 +00003734 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003735 {
3736 unsigned Size = Record.size();
3737 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003738 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003739 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003740 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003741 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003742
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003743 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003744 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003745 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003746 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003747 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003748 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003749
Chris Lattnerf1c87102011-06-17 18:09:11 +00003750 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003751 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003752 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003753 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003754 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003755 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003756 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003757 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003758 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003759 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003760
Devang Patelaf206b82009-09-18 19:26:43 +00003761 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003762 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003763 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003764 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003765 else {
3766 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003767 Value *Cond = getValue(Record, 2, NextValueNo,
3768 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003769 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003770 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003771 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003772 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003773 }
3774 break;
3775 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00003776 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003777 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003778 return error("Invalid record");
3779 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003780 Value *CleanupPad =
3781 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003782 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00003783 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003784 BasicBlock *UnwindDest = nullptr;
3785 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00003786 UnwindDest = getBasicBlock(Record[Idx++]);
3787 if (!UnwindDest)
3788 return error("Invalid record");
3789 }
3790
David Majnemer8a1c45d2015-12-12 05:38:55 +00003791 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00003792 InstructionList.push_back(I);
3793 break;
3794 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003795 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3796 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003797 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003798 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003799 Value *CatchPad =
3800 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003801 if (!CatchPad)
3802 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003803 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00003804 if (!BB)
3805 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003806
David Majnemer8a1c45d2015-12-12 05:38:55 +00003807 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00003808 InstructionList.push_back(I);
3809 break;
3810 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003811 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3812 // We must have, at minimum, the outer scope and the number of arguments.
3813 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003814 return error("Invalid record");
3815
David Majnemer654e1302015-07-31 17:58:14 +00003816 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003817
3818 Value *ParentPad =
3819 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3820
3821 unsigned NumHandlers = Record[Idx++];
3822
3823 SmallVector<BasicBlock *, 2> Handlers;
3824 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3825 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3826 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00003827 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003828 Handlers.push_back(BB);
3829 }
3830
3831 BasicBlock *UnwindDest = nullptr;
3832 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00003833 UnwindDest = getBasicBlock(Record[Idx++]);
3834 if (!UnwindDest)
3835 return error("Invalid record");
3836 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003837
3838 if (Record.size() != Idx)
3839 return error("Invalid record");
3840
3841 auto *CatchSwitch =
3842 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3843 for (BasicBlock *Handler : Handlers)
3844 CatchSwitch->addHandler(Handler);
3845 I = CatchSwitch;
3846 InstructionList.push_back(I);
3847 break;
3848 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003849 case bitc::FUNC_CODE_INST_CATCHPAD:
3850 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3851 // We must have, at minimum, the outer scope and the number of arguments.
3852 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003853 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003854
David Majnemer654e1302015-07-31 17:58:14 +00003855 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003856
3857 Value *ParentPad =
3858 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3859
David Majnemer654e1302015-07-31 17:58:14 +00003860 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00003861
David Majnemer654e1302015-07-31 17:58:14 +00003862 SmallVector<Value *, 2> Args;
3863 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3864 Value *Val;
3865 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3866 return error("Invalid record");
3867 Args.push_back(Val);
3868 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003869
David Majnemer654e1302015-07-31 17:58:14 +00003870 if (Record.size() != Idx)
3871 return error("Invalid record");
3872
David Majnemer8a1c45d2015-12-12 05:38:55 +00003873 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3874 I = CleanupPadInst::Create(ParentPad, Args);
3875 else
3876 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003877 InstructionList.push_back(I);
3878 break;
3879 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003880 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003881 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003882 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003883 // "New" SwitchInst format with case ranges. The changes to write this
3884 // format were reverted but we still recognize bitcode that uses it.
3885 // Hopefully someday we will have support for case ranges and can use
3886 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003887
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003888 Type *OpTy = getTypeByID(Record[1]);
3889 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3890
Jan Wen Voungafaced02012-10-11 20:20:40 +00003891 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003892 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003893 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003894 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003895
3896 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003897
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003898 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3899 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003900
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003901 unsigned CurIdx = 5;
3902 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003903 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003904 unsigned NumItems = Record[CurIdx++];
3905 for (unsigned ci = 0; ci != NumItems; ++ci) {
3906 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003907
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003908 APInt Low;
3909 unsigned ActiveWords = 1;
3910 if (ValueBitWidth > 64)
3911 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003912 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003913 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003914 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003915
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003916 if (!isSingleNumber) {
3917 ActiveWords = 1;
3918 if (ValueBitWidth > 64)
3919 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003920 APInt High = readWideAPInt(
3921 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003922 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003923
3924 // FIXME: It is not clear whether values in the range should be
3925 // compared as signed or unsigned values. The partially
3926 // implemented changes that used this format in the past used
3927 // unsigned comparisons.
3928 for ( ; Low.ule(High); ++Low)
3929 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003930 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003931 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003932 }
3933 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00003934 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3935 cve = CaseVals.end(); cvi != cve; ++cvi)
3936 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003937 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003938 I = SI;
3939 break;
3940 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003941
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003942 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003943
Chris Lattner5285b5e2007-05-02 05:46:45 +00003944 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003945 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003946 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003947 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003948 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003949 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003950 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003951 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00003952 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00003953 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003954 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003955 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00003956 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3957 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003958 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00003959 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003960 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003961 }
3962 SI->addCase(CaseVal, DestBB);
3963 }
3964 I = SI;
3965 break;
3966 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003967 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00003968 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003969 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003970 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003971 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003972 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003973 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003974 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003975 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00003976 InstructionList.push_back(IBI);
3977 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3978 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3979 IBI->addDestination(DestBB);
3980 } else {
3981 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003982 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003983 }
3984 }
3985 I = IBI;
3986 break;
3987 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003988
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003989 case bitc::FUNC_CODE_INST_INVOKE: {
3990 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003991 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003992 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003993 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00003994 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003995 unsigned CCInfo = Record[OpNum++];
3996 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3997 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003998
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003999 FunctionType *FTy = nullptr;
4000 if (CCInfo >> 13 & 1 &&
4001 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004002 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004003
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004004 Value *Callee;
4005 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004006 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004007
Chris Lattner229907c2011-07-18 04:54:35 +00004008 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004009 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004010 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004011 if (!FTy) {
4012 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4013 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004014 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004015 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004016 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004017 "callee operand");
4018 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004019 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004020
Chris Lattner5285b5e2007-05-02 05:46:45 +00004021 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004022 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004023 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4024 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004025 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004026 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004027 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004028
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004029 if (!FTy->isVarArg()) {
4030 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004031 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004032 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004033 // Read type/value pairs for varargs params.
4034 while (OpNum != Record.size()) {
4035 Value *Op;
4036 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004037 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004038 Ops.push_back(Op);
4039 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004040 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004041
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004042 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4043 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004044 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004045 cast<InvokeInst>(I)->setCallingConv(
4046 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004047 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004048 break;
4049 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004050 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4051 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004052 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004053 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004054 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004055 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004056 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004057 break;
4058 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004059 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004060 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004061 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004062 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004063 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004064 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004065 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004066 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004067 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004068 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004069
Jay Foad52131342011-03-30 11:28:46 +00004070 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004071 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004072
Chris Lattnere14cb882007-05-04 19:11:41 +00004073 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004074 Value *V;
4075 // With the new function encoding, it is possible that operands have
4076 // negative IDs (for forward references). Use a signed VBR
4077 // representation to keep the encoding small.
4078 if (UseRelativeIDs)
4079 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4080 else
4081 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004082 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004083 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004084 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004085 PN->addIncoming(V, BB);
4086 }
4087 I = PN;
4088 break;
4089 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004090
David Majnemer7fddecc2015-06-17 20:52:32 +00004091 case bitc::FUNC_CODE_INST_LANDINGPAD:
4092 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004093 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4094 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004095 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4096 if (Record.size() < 3)
4097 return error("Invalid record");
4098 } else {
4099 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4100 if (Record.size() < 4)
4101 return error("Invalid record");
4102 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004103 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004104 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004105 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004106 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4107 Value *PersFn = nullptr;
4108 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4109 return error("Invalid record");
4110
4111 if (!F->hasPersonalityFn())
4112 F->setPersonalityFn(cast<Constant>(PersFn));
4113 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4114 return error("Personality function mismatch");
4115 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004116
4117 bool IsCleanup = !!Record[Idx++];
4118 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004119 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004120 LP->setCleanup(IsCleanup);
4121 for (unsigned J = 0; J != NumClauses; ++J) {
4122 LandingPadInst::ClauseType CT =
4123 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4124 Value *Val;
4125
4126 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4127 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004128 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004129 }
4130
4131 assert((CT != LandingPadInst::Catch ||
4132 !isa<ArrayType>(Val->getType())) &&
4133 "Catch clause has a invalid type!");
4134 assert((CT != LandingPadInst::Filter ||
4135 isa<ArrayType>(Val->getType())) &&
4136 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004137 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004138 }
4139
4140 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004141 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004142 break;
4143 }
4144
Chris Lattnerf1c87102011-06-17 18:09:11 +00004145 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4146 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004147 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004148 uint64_t AlignRecord = Record[3];
4149 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004150 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004151 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4152 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4153 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004154 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004155 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004156 Type *Ty = getTypeByID(Record[0]);
4157 if ((AlignRecord & ExplicitTypeMask) == 0) {
4158 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4159 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004160 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004161 Ty = PTy->getElementType();
4162 }
4163 Type *OpTy = getTypeByID(Record[1]);
4164 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004165 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004166 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4167 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004168 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004169 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004170 return error("Invalid record");
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004171
4172 // FIXME: Make this an optional field.
4173 const DataLayout &DL = TheModule->getDataLayout();
4174 unsigned AS = DL.getAllocaAddrSpace();
4175
4176 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004177 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00004178 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004179 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004180 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004181 break;
4182 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004183 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004184 unsigned OpNum = 0;
4185 Value *Op;
4186 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004187 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004188 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004189
4190 Type *Ty = nullptr;
4191 if (OpNum + 3 == Record.size())
4192 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004193 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4194 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004195 if (!Ty)
4196 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004197
JF Bastien30bf96b2015-02-22 19:32:03 +00004198 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004199 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4200 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004201 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004202
Devang Patelaf206b82009-09-18 19:26:43 +00004203 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004204 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004205 }
Eli Friedman59b66882011-08-09 23:02:53 +00004206 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4207 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4208 unsigned OpNum = 0;
4209 Value *Op;
4210 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004211 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004212 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004213
David Blaikie85035652015-02-25 01:07:20 +00004214 Type *Ty = nullptr;
4215 if (OpNum + 5 == Record.size())
4216 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004217 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4218 return Err;
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004219 if (!Ty)
4220 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004221
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004222 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004223 if (Ordering == AtomicOrdering::NotAtomic ||
4224 Ordering == AtomicOrdering::Release ||
4225 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004226 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00004227 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004228 return error("Invalid record");
4229 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004230
JF Bastien30bf96b2015-02-22 19:32:03 +00004231 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004232 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4233 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004234 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004235
Eli Friedman59b66882011-08-09 23:02:53 +00004236 InstructionList.push_back(I);
4237 break;
4238 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004239 case bitc::FUNC_CODE_INST_STORE:
4240 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004241 unsigned OpNum = 0;
4242 Value *Val, *Ptr;
4243 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004244 (BitCode == bitc::FUNC_CODE_INST_STORE
4245 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4246 : popValue(Record, OpNum, NextValueNo,
4247 cast<PointerType>(Ptr->getType())->getElementType(),
4248 Val)) ||
4249 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004250 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004251
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004252 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4253 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004254 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004255 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4256 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004257 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004258 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004259 break;
4260 }
David Blaikie50a06152015-04-22 04:14:46 +00004261 case bitc::FUNC_CODE_INST_STOREATOMIC:
4262 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004263 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4264 unsigned OpNum = 0;
4265 Value *Val, *Ptr;
4266 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00004267 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00004268 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4269 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4270 : popValue(Record, OpNum, NextValueNo,
4271 cast<PointerType>(Ptr->getType())->getElementType(),
4272 Val)) ||
4273 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004274 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004275
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004276 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4277 return Err;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004278 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004279 if (Ordering == AtomicOrdering::NotAtomic ||
4280 Ordering == AtomicOrdering::Acquire ||
4281 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004282 return error("Invalid record");
4283 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00004284 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004285 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004286
JF Bastien30bf96b2015-02-22 19:32:03 +00004287 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004288 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4289 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004290 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004291 InstructionList.push_back(I);
4292 break;
4293 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004294 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004295 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004296 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004297 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004298 unsigned OpNum = 0;
4299 Value *Ptr, *Cmp, *New;
4300 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004301 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4302 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4303 : popValue(Record, OpNum, NextValueNo,
4304 cast<PointerType>(Ptr->getType())->getElementType(),
4305 Cmp)) ||
4306 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4307 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004308 return error("Invalid record");
4309 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00004310 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4311 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004312 return error("Invalid record");
4313 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004314
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004315 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4316 return Err;
Tim Northovere94a5182014-03-11 10:48:52 +00004317 AtomicOrdering FailureOrdering;
4318 if (Record.size() < 7)
4319 FailureOrdering =
4320 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4321 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004322 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004323
4324 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4325 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004326 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004327
4328 if (Record.size() < 8) {
4329 // Before weak cmpxchgs existed, the instruction simply returned the
4330 // value loaded from memory, so bitcode files from that era will be
4331 // expecting the first component of a modern cmpxchg.
4332 CurBB->getInstList().push_back(I);
4333 I = ExtractValueInst::Create(I, 0);
4334 } else {
4335 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4336 }
4337
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004338 InstructionList.push_back(I);
4339 break;
4340 }
4341 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4342 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4343 unsigned OpNum = 0;
4344 Value *Ptr, *Val;
4345 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00004346 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004347 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004348 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4349 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004350 return error("Invalid record");
4351 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004352 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4353 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004354 return error("Invalid record");
4355 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004356 if (Ordering == AtomicOrdering::NotAtomic ||
4357 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004358 return error("Invalid record");
4359 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004360 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4361 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4362 InstructionList.push_back(I);
4363 break;
4364 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00004365 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4366 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004367 return error("Invalid record");
4368 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00004369 if (Ordering == AtomicOrdering::NotAtomic ||
4370 Ordering == AtomicOrdering::Unordered ||
4371 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004372 return error("Invalid record");
4373 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004374 I = new FenceInst(Context, Ordering, SynchScope);
4375 InstructionList.push_back(I);
4376 break;
4377 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004378 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004379 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004380 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004381 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004382
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004383 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004384 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004385 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004386
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004387 FastMathFlags FMF;
4388 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4389 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4390 if (!FMF.any())
4391 return error("Fast math flags indicator set for call with no FMF");
4392 }
4393
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004394 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004395 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004396 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004397 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004398
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004399 Value *Callee;
4400 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004401 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004402
Chris Lattner229907c2011-07-18 04:54:35 +00004403 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004404 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004405 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004406 if (!FTy) {
4407 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4408 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004409 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00004410 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004411 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004412 "callee operand");
4413 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004414 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004415
Chris Lattner9f600c52007-05-03 22:04:19 +00004416 SmallVector<Value*, 16> Args;
4417 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004418 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004419 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004420 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004421 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004422 Args.push_back(getValue(Record, OpNum, NextValueNo,
4423 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004424 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004425 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004426 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004427
Chris Lattner9f600c52007-05-03 22:04:19 +00004428 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004429 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004430 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004431 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004432 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004433 while (OpNum != Record.size()) {
4434 Value *Op;
4435 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004436 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004437 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004438 }
4439 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004440
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004441 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4442 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004443 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004444 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004445 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00004446 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004447 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00004448 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004449 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00004450 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004451 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004452 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00004453 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004454 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004455 if (FMF.any()) {
4456 if (!isa<FPMathOperator>(I))
4457 return error("Fast-math-flags specified for call without "
4458 "floating-point scalar or vector return type");
4459 I->setFastMathFlags(FMF);
4460 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004461 break;
4462 }
4463 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4464 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004465 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004466 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004467 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004468 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004469 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004470 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004471 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004472 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004473 break;
4474 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004475
4476 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4477 // A call or an invoke can be optionally prefixed with some variable
4478 // number of operand bundle blocks. These blocks are read into
4479 // OperandBundles and consumed at the next call or invoke instruction.
4480
4481 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4482 return error("Invalid record");
4483
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004484 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004485
4486 unsigned OpNum = 1;
4487 while (OpNum != Record.size()) {
4488 Value *Op;
4489 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4490 return error("Invalid record");
4491 Inputs.push_back(Op);
4492 }
4493
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004494 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004495 continue;
4496 }
Chris Lattner83930552007-05-01 07:01:57 +00004497 }
4498
4499 // Add instruction to end of current BB. If there is no current BB, reject
4500 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004501 if (!CurBB) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004502 I->deleteValue();
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004503 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004504 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004505 if (!OperandBundles.empty()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004506 I->deleteValue();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004507 return error("Operand bundles found with no consumer");
4508 }
Chris Lattner83930552007-05-01 07:01:57 +00004509 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004510
Chris Lattner83930552007-05-01 07:01:57 +00004511 // If this was a terminator instruction, move to the next block.
4512 if (isa<TerminatorInst>(I)) {
4513 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004514 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004515 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004516
Chris Lattner83930552007-05-01 07:01:57 +00004517 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004518 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00004519 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004520 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004521
Chris Lattner27d38752013-01-20 02:13:19 +00004522OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004523
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004524 if (!OperandBundles.empty())
4525 return error("Operand bundles found with no consumer");
4526
Chris Lattner83930552007-05-01 07:01:57 +00004527 // Check the function list for unresolved values.
4528 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004529 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004530 // We found at least one unresolved value. Nuke them all to avoid leaks.
4531 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004532 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004533 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004534 delete A;
4535 }
4536 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004537 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004538 }
Chris Lattner83930552007-05-01 07:01:57 +00004539 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004540
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004541 // Unexpected unresolved metadata about to be dropped.
Mehdi Aminief27db82016-12-12 19:34:26 +00004542 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004543 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00004544
Chris Lattner85b7b402007-05-01 05:52:21 +00004545 // Trim the value list down to the size it was before we parsed this function.
4546 ValueList.shrinkTo(ModuleValueListSize);
Mehdi Aminief27db82016-12-12 19:34:26 +00004547 MDLoader->shrinkTo(ModuleMDLoaderSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004548 std::vector<BasicBlock*>().swap(FunctionBBs);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004549 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004550}
4551
Rafael Espindola7d712032013-11-05 17:16:08 +00004552/// Find the function body in the bitcode stream
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004553Error BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004554 Function *F,
4555 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004556 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00004557 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00004558 // didn't contain the function index in the VST, or when we have
4559 // an anonymous function which would not have a VST entry.
4560 // Assert that we have one of those two cases.
4561 assert(VSTOffset == 0 || !F->hasName());
4562 // Parse the next body in the stream and set its position in the
4563 // DeferredFunctionInfo map.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004564 if (Error Err = rememberAndSkipFunctionBodies())
4565 return Err;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004566 }
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004567 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004568}
4569
Chris Lattner9eeada92007-05-18 04:02:46 +00004570//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004571// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004572//===----------------------------------------------------------------------===//
4573
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004574Error BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004575 Function *F = dyn_cast<Function>(GV);
4576 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004577 if (!F || !F->isMaterializable())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004578 return Error::success();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004579
4580 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004581 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004582 // If its position is recorded as 0, its body is somewhere in the stream
4583 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004584 if (DFII->second == 0)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004585 if (Error Err = findFunctionInStream(F, DFII))
4586 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004587
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004588 // Materialize metadata before parsing any function bodies.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004589 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004590 return Err;
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004591
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004592 // Move the bit stream to the saved position of the deferred function body.
4593 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004594
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004595 if (Error Err = parseFunctionBody(F))
4596 return Err;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004597 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004598
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004599 if (StripDebugInfo)
4600 stripDebugInfo(*F);
4601
Chandler Carruth7132e002007-08-04 01:51:18 +00004602 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004603 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00004604 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4605 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004606 User *U = *UI;
4607 ++UI;
4608 if (CallInst *CI = dyn_cast<CallInst>(U))
4609 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004610 }
4611 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004612
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004613 // Update calls to the remangled intrinsics
4614 for (auto &I : RemangledIntrinsics)
4615 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4616 UI != UE;)
4617 // Don't expect any other users than call sites
4618 CallSite(*UI++).setCalledFunction(I.second);
4619
Peter Collingbourned4bff302015-11-05 22:03:56 +00004620 // Finish fn->subprogram upgrade for materialized functions.
Mehdi Aminief27db82016-12-12 19:34:26 +00004621 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
Peter Collingbourned4bff302015-11-05 22:03:56 +00004622 F->setSubprogram(SP);
4623
Mehdi Amini86623052016-12-16 19:16:29 +00004624 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4625 if (!MDLoader->isStrippingTBAA()) {
4626 for (auto &I : instructions(F)) {
4627 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4628 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4629 continue;
4630 MDLoader->setStripTBAA(true);
4631 stripTBAA(F->getParent());
4632 }
4633 }
4634
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004635 // Bring in any functions that this function forward-referenced via
4636 // blockaddresses.
4637 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004638}
4639
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004640Error BitcodeReader::materializeModule() {
4641 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004642 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004643
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004644 // Promise to materialize all forward references.
4645 WillMaterializeAllForwardRefs = true;
4646
Chris Lattner06310bf2009-06-16 05:15:21 +00004647 // Iterate over the module, deserializing any functions that are still on
4648 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004649 for (Function &F : *TheModule) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004650 if (Error Err = materialize(&F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004651 return Err;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004652 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00004653 // At this point, if there are any function bodies, parse the rest of
4654 // the bits in the module past the last function block we have recorded
4655 // through either lazy scanning or the VST.
4656 if (LastFunctionBlockBit || NextUnreadBit)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004657 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4658 ? LastFunctionBlockBit
4659 : NextUnreadBit))
4660 return Err;
Derek Schuff92ef9752012-02-29 00:07:09 +00004661
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004662 // Check that all block address forward references got resolved (as we
4663 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004664 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004665 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004666
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004667 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4668 // delete the old functions to clean up. We can't do this unless the entire
4669 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004670 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004671 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004672 for (auto *U : I.first->users()) {
4673 if (CallInst *CI = dyn_cast<CallInst>(U))
4674 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004675 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004676 if (!I.first->use_empty())
4677 I.first->replaceAllUsesWith(I.second);
4678 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004679 }
Rafael Espindola4e721212015-07-02 16:22:40 +00004680 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004681 // Do the same for remangled intrinsics
4682 for (auto &I : RemangledIntrinsics) {
4683 I.first->replaceAllUsesWith(I.second);
4684 I.first->eraseFromParent();
4685 }
4686 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00004687
Rafael Espindola79753a02015-12-18 21:18:57 +00004688 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00004689
4690 UpgradeModuleFlags(*TheModule);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004691 return Error::success();
Chris Lattner9eeada92007-05-18 04:02:46 +00004692}
4693
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004694std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4695 return IdentifiedStructTypes;
4696}
4697
Teresa Johnson26ab5772016-03-15 00:04:37 +00004698ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004699 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4700 StringRef ModulePath, unsigned ModuleId)
4701 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4702 ModulePath(ModulePath), ModuleId(ModuleId) {}
4703
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00004704ModuleSummaryIndex::ModuleInfo *
4705ModuleSummaryIndexBitcodeReader::addThisModule() {
4706 return TheIndex.addModule(ModulePath, ModuleId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004707}
Teresa Johnson403a7872015-10-04 14:33:43 +00004708
Peter Collingbourne9667b912017-05-04 18:03:25 +00004709std::pair<ValueInfo, GlobalValue::GUID>
4710ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4711 auto VGI = ValueIdToValueInfoMap[ValueId];
4712 assert(VGI.first);
4713 return VGI;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004714}
4715
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004716void ModuleSummaryIndexBitcodeReader::setValueGUID(
4717 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4718 StringRef SourceFileName) {
4719 std::string GlobalId =
4720 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4721 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4722 auto OriginalNameID = ValueGUID;
4723 if (GlobalValue::isLocalLinkage(Linkage))
4724 OriginalNameID = GlobalValue::getGUID(ValueName);
4725 if (PrintSummaryGUIDs)
4726 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4727 << ValueName << "\n";
Peter Collingbourne9667b912017-05-04 18:03:25 +00004728 ValueIdToValueInfoMap[ValueID] =
4729 std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004730}
4731
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004732// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00004733// blocks where we don't actually create global values. The parsed information
4734// is saved in the bitcode reader for use when later parsing summaries.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004735Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004736 uint64_t Offset,
4737 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004738 // With a strtab the VST is not required to parse the summary.
4739 if (UseStrtab)
4740 return Error::success();
4741
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004742 assert(Offset > 0 && "Expected non-zero VST offset");
4743 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4744
Teresa Johnson403a7872015-10-04 14:33:43 +00004745 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4746 return error("Invalid record");
4747
4748 SmallVector<uint64_t, 64> Record;
4749
4750 // Read all the records for this value table.
4751 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004752
4753 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004754 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4755
4756 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004757 case BitstreamEntry::SubBlock: // Handled for us already.
4758 case BitstreamEntry::Error:
4759 return error("Malformed block");
4760 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004761 // Done parsing VST, jump back to wherever we came from.
4762 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004763 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004764 case BitstreamEntry::Record:
4765 // The interesting case.
4766 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00004767 }
4768
4769 // Read a record.
4770 Record.clear();
4771 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004772 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4773 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004774 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4775 if (convertToString(Record, 1, ValueName))
4776 return error("Invalid record");
4777 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004778 assert(!SourceFileName.empty());
4779 auto VLI = ValueIdToLinkageMap.find(ValueID);
4780 assert(VLI != ValueIdToLinkageMap.end() &&
4781 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004782 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004783 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004784 ValueName.clear();
4785 break;
4786 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004787 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00004788 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004789 if (convertToString(Record, 2, ValueName))
4790 return error("Invalid record");
4791 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004792 assert(!SourceFileName.empty());
4793 auto VLI = ValueIdToLinkageMap.find(ValueID);
4794 assert(VLI != ValueIdToLinkageMap.end() &&
4795 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004796 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004797 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004798 ValueName.clear();
4799 break;
4800 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004801 case bitc::VST_CODE_COMBINED_ENTRY: {
4802 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4803 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00004804 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004805 // The "original name", which is the second value of the pair will be
4806 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
Peter Collingbourne9667b912017-05-04 18:03:25 +00004807 ValueIdToValueInfoMap[ValueID] =
4808 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004809 break;
4810 }
Teresa Johnson403a7872015-10-04 14:33:43 +00004811 }
4812 }
4813}
4814
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004815// Parse just the blocks needed for building the index out of the module.
4816// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00004817// from global value id to GlobalValueSummary objects.
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004818Error ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00004819 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4820 return error("Invalid record");
4821
Teresa Johnsone1164de2016-02-10 21:55:02 +00004822 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004823 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4824 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004825
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004826 // Read the index for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004827 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004828 BitstreamEntry Entry = Stream.advance();
4829
4830 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004831 case BitstreamEntry::Error:
4832 return error("Malformed block");
4833 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004834 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004835
4836 case BitstreamEntry::SubBlock:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004837 switch (Entry.ID) {
4838 default: // Skip unknown content.
4839 if (Stream.SkipBlock())
4840 return error("Invalid record");
4841 break;
4842 case bitc::BLOCKINFO_BLOCK_ID:
4843 // Need to parse these to get abbrev ids (e.g. for VST)
Peter Collingbourne939c7d92016-11-08 04:16:57 +00004844 if (readBlockInfo())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004845 return error("Malformed block");
4846 break;
4847 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004848 // Should have been parsed earlier via VSTOffset, unless there
4849 // is no summary section.
4850 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4851 !SeenGlobalValSummary) &&
4852 "Expected early VST parse via VSTOffset record");
4853 if (Stream.SkipBlock())
4854 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004855 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004856 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00004857 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004858 assert(!SeenValueSymbolTable &&
4859 "Already read VST when parsing summary block?");
Teresa Johnson620c1402016-09-20 23:07:17 +00004860 // We might not have a VST if there were no values in the
4861 // summary. An empty summary block generated when we are
4862 // performing ThinLTO compiles so we don't later invoke
4863 // the regular LTO process on them.
4864 if (VSTOffset > 0) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004865 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4866 return Err;
Teresa Johnson620c1402016-09-20 23:07:17 +00004867 SeenValueSymbolTable = true;
4868 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004869 SeenGlobalValSummary = true;
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00004870 if (Error Err = parseEntireSummary(Entry.ID))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004871 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004872 break;
4873 case bitc::MODULE_STRTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004874 if (Error Err = parseModuleStringTable())
4875 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004876 break;
4877 }
4878 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00004879
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004880 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004881 Record.clear();
4882 auto BitCode = Stream.readRecord(Entry.ID, Record);
4883 switch (BitCode) {
4884 default:
4885 break; // Default behavior, ignore unknown content.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004886 case bitc::MODULE_CODE_VERSION: {
4887 if (Error Err = parseVersionRecord(Record).takeError())
4888 return Err;
4889 break;
4890 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00004891 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004892 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004893 SmallString<128> ValueName;
4894 if (convertToString(Record, 0, ValueName))
4895 return error("Invalid record");
4896 SourceFileName = ValueName.c_str();
4897 break;
4898 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004899 /// MODULE_CODE_HASH: [5*i32]
4900 case bitc::MODULE_CODE_HASH: {
4901 if (Record.size() != 5)
4902 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00004903 auto &Hash = addThisModule()->second.second;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004904 int Pos = 0;
4905 for (auto &Val : Record) {
4906 assert(!(Val >> 32) && "Unexpected high bits set");
4907 Hash[Pos++] = Val;
4908 }
4909 break;
4910 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004911 /// MODULE_CODE_VSTOFFSET: [offset]
4912 case bitc::MODULE_CODE_VSTOFFSET:
4913 if (Record.size() < 1)
4914 return error("Invalid record");
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00004915 // Note that we subtract 1 here because the offset is relative to one
4916 // word before the start of the identification or module block, which
4917 // was historically always the start of the regular bitcode header.
4918 VSTOffset = Record[0] - 1;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004919 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004920 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
4921 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
4922 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
4923 // v2: [strtab offset, strtab size, v1]
Peter Collingbournef43e0ae2017-04-10 21:17:54 +00004924 case bitc::MODULE_CODE_GLOBALVAR:
4925 case bitc::MODULE_CODE_FUNCTION:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004926 case bitc::MODULE_CODE_ALIAS: {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004927 StringRef Name;
4928 ArrayRef<uint64_t> GVRecord;
4929 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
4930 if (GVRecord.size() <= 3)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004931 return error("Invalid record");
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004932 uint64_t RawLinkage = GVRecord[3];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004933 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004934 if (!UseStrtab) {
4935 ValueIdToLinkageMap[ValueId++] = Linkage;
4936 break;
4937 }
4938
4939 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004940 break;
4941 }
4942 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00004943 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004944 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00004945 }
4946 }
4947}
4948
Peter Collingbourne0c30f082016-12-20 21:12:28 +00004949std::vector<ValueInfo>
4950ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
4951 std::vector<ValueInfo> Ret;
4952 Ret.reserve(Record.size());
4953 for (uint64_t RefValueId : Record)
Peter Collingbourne9667b912017-05-04 18:03:25 +00004954 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00004955 return Ret;
4956}
4957
4958std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
4959 ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
4960 std::vector<FunctionSummary::EdgeTy> Ret;
4961 Ret.reserve(Record.size());
4962 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
4963 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
Peter Collingbourne9667b912017-05-04 18:03:25 +00004964 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00004965 if (IsOldProfileFormat) {
4966 I += 1; // Skip old callsitecount field
4967 if (HasProfile)
4968 I += 1; // Skip old profilecount field
4969 } else if (HasProfile)
4970 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00004971 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}});
Peter Collingbourne0c30f082016-12-20 21:12:28 +00004972 }
4973 return Ret;
4974}
4975
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004976// Eagerly parse the entire summary block. This populates the GlobalValueSummary
4977// objects in the index.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00004978Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
4979 if (Stream.EnterSubBlock(ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00004980 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00004981 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00004982
4983 // Parse version
4984 {
4985 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4986 if (Entry.Kind != BitstreamEntry::Record)
4987 return error("Invalid Summary Block: record for version expected");
4988 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
4989 return error("Invalid Summary Block: version expected");
4990 }
4991 const uint64_t Version = Record[0];
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00004992 const bool IsOldProfileFormat = Version == 1;
Teresa Johnson519465b2017-01-05 14:32:16 +00004993 if (Version < 1 || Version > 3)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00004994 return error("Invalid summary version " + Twine(Version) +
Teresa Johnson519465b2017-01-05 14:32:16 +00004995 ", 1, 2 or 3 expected");
Mehdi Amini8fe69362016-04-24 03:18:11 +00004996 Record.clear();
4997
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004998 // Keep around the last seen summary to be used when we see an optional
4999 // "OriginalName" attachement.
5000 GlobalValueSummary *LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005001 GlobalValue::GUID LastSeenGUID = 0;
Peter Collingbournefa3175f2017-02-11 03:19:22 +00005002
5003 // We can expect to see any number of type ID information records before
5004 // each function summary records; these variables store the information
5005 // collected so far so that it can be used to create the summary object.
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005006 std::vector<GlobalValue::GUID> PendingTypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005007 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5008 PendingTypeCheckedLoadVCalls;
5009 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5010 PendingTypeCheckedLoadConstVCalls;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005011
5012 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005013 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5014
5015 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005016 case BitstreamEntry::SubBlock: // Handled for us already.
5017 case BitstreamEntry::Error:
5018 return error("Malformed block");
5019 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005020 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005021 case BitstreamEntry::Record:
5022 // The interesting case.
5023 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005024 }
5025
5026 // Read a record. The record format depends on whether this
5027 // is a per-module index or a combined index file. In the per-module
5028 // case the records contain the associated value's ID for correlation
5029 // with VST entries. In the combined index the correlation is done
5030 // via the bitcode offset of the summary records (which were saved
5031 // in the combined index VST entries). The records also contain
5032 // information used for ThinLTO renaming and importing.
5033 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005034 auto BitCode = Stream.readRecord(Entry.ID, Record);
5035 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005036 default: // Default behavior: ignore.
5037 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005038 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5039 uint64_t ValueID = Record[0];
5040 GlobalValue::GUID RefGUID = Record[1];
Peter Collingbourne9667b912017-05-04 18:03:25 +00005041 ValueIdToValueInfoMap[ValueID] =
5042 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005043 break;
5044 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005045 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005046 // n x (valueid)]
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005047 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005048 // numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005049 // n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005050 case bitc::FS_PERMODULE:
5051 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005052 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005053 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005054 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005055 unsigned NumRefs = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005056 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005057 // The module path string ref set in the summary must be owned by the
5058 // index's module string table. Since we don't have a module path
5059 // string table section in the per-module index, we create a single
5060 // module path string table entry with an empty (0) ID to take
5061 // ownership.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005062 static int RefListStartIndex = 4;
5063 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5064 assert(Record.size() >= RefListStartIndex + NumRefs &&
5065 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005066 std::vector<ValueInfo> Refs = makeRefList(
5067 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005068 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005069 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5070 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5071 IsOldProfileFormat, HasProfile);
5072 auto FS = llvm::make_unique<FunctionSummary>(
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005073 Flags, InstCount, std::move(Refs), std::move(Calls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005074 std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5075 std::move(PendingTypeCheckedLoadVCalls),
5076 std::move(PendingTypeTestAssumeConstVCalls),
5077 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005078 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005079 PendingTypeTestAssumeVCalls.clear();
5080 PendingTypeCheckedLoadVCalls.clear();
5081 PendingTypeTestAssumeConstVCalls.clear();
5082 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005083 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005084 FS->setModulePath(addThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005085 FS->setOriginalName(VIAndOriginalGUID.second);
5086 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005087 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005088 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005089 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005090 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5091 // they expect all aliasee summaries to be available.
5092 case bitc::FS_ALIAS: {
5093 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005094 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005095 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005096 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005097 auto AS =
5098 llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005099 // The module path string ref set in the summary must be owned by the
5100 // index's module string table. Since we don't have a module path
5101 // string table section in the per-module index, we create a single
5102 // module path string table entry with an empty (0) ID to take
5103 // ownership.
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005104 AS->setModulePath(addThisModule()->first());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005105
Peter Collingbourne9667b912017-05-04 18:03:25 +00005106 GlobalValue::GUID AliaseeGUID =
5107 getValueInfoFromValueId(AliaseeID).first.getGUID();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005108 auto AliaseeInModule =
5109 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5110 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005111 return error("Alias expects aliasee summary to be parsed");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005112 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005113
Peter Collingbourne9667b912017-05-04 18:03:25 +00005114 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005115 AS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005116 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005117 break;
5118 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005119 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005120 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5121 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005122 uint64_t RawFlags = Record[1];
5123 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005124 std::vector<ValueInfo> Refs =
5125 makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5126 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005127 FS->setModulePath(addThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005128 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005129 FS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005130 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005131 break;
5132 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005133 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005134 // numrefs x valueid, n x (valueid)]
Teresa Johnson02e98332016-04-27 13:28:35 +00005135 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005136 // numrefs x valueid, n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005137 case bitc::FS_COMBINED:
5138 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005139 unsigned ValueID = Record[0];
5140 uint64_t ModuleId = Record[1];
5141 uint64_t RawFlags = Record[2];
5142 unsigned InstCount = Record[3];
5143 unsigned NumRefs = Record[4];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005144 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson02e98332016-04-27 13:28:35 +00005145 static int RefListStartIndex = 5;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005146 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5147 assert(Record.size() >= RefListStartIndex + NumRefs &&
5148 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005149 std::vector<ValueInfo> Refs = makeRefList(
5150 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005151 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005152 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5153 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5154 IsOldProfileFormat, HasProfile);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005155 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005156 auto FS = llvm::make_unique<FunctionSummary>(
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005157 Flags, InstCount, std::move(Refs), std::move(Edges),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005158 std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5159 std::move(PendingTypeCheckedLoadVCalls),
5160 std::move(PendingTypeTestAssumeConstVCalls),
5161 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005162 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005163 PendingTypeTestAssumeVCalls.clear();
5164 PendingTypeCheckedLoadVCalls.clear();
5165 PendingTypeTestAssumeConstVCalls.clear();
5166 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005167 LastSeenSummary = FS.get();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005168 LastSeenGUID = VI.getGUID();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005169 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005170 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005171 break;
5172 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005173 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005174 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5175 // they expect all aliasee summaries to be available.
5176 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005177 unsigned ValueID = Record[0];
5178 uint64_t ModuleId = Record[1];
5179 uint64_t RawFlags = Record[2];
5180 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005181 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005182 auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005183 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005184 AS->setModulePath(ModuleIdMap[ModuleId]);
5185
Peter Collingbourne9667b912017-05-04 18:03:25 +00005186 auto AliaseeGUID =
5187 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
Teresa Johnson02e98332016-04-27 13:28:35 +00005188 auto AliaseeInModule =
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005189 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
Teresa Johnson02e98332016-04-27 13:28:35 +00005190 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005191 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00005192 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005193
Peter Collingbourne9667b912017-05-04 18:03:25 +00005194 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5195 LastSeenGUID = VI.getGUID();
5196 TheIndex.addGlobalValueSummary(VI, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005197 break;
5198 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005199 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005200 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005201 unsigned ValueID = Record[0];
5202 uint64_t ModuleId = Record[1];
5203 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005204 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005205 std::vector<ValueInfo> Refs =
5206 makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5207 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005208 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005209 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005210 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5211 LastSeenGUID = VI.getGUID();
5212 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005213 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005214 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005215 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5216 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5217 uint64_t OriginalName = Record[0];
5218 if (!LastSeenSummary)
5219 return error("Name attachment that does not follow a combined record");
5220 LastSeenSummary->setOriginalName(OriginalName);
Dehao Chen4a435e02017-03-14 17:33:01 +00005221 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005222 // Reset the LastSeenSummary
5223 LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005224 LastSeenGUID = 0;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005225 break;
5226 }
5227 case bitc::FS_TYPE_TESTS: {
5228 assert(PendingTypeTests.empty());
5229 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5230 Record.end());
5231 break;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005232 }
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005233 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: {
5234 assert(PendingTypeTestAssumeVCalls.empty());
5235 for (unsigned I = 0; I != Record.size(); I += 2)
5236 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5237 break;
5238 }
5239 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: {
5240 assert(PendingTypeCheckedLoadVCalls.empty());
5241 for (unsigned I = 0; I != Record.size(); I += 2)
5242 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5243 break;
5244 }
5245 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: {
5246 PendingTypeTestAssumeConstVCalls.push_back(
5247 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5248 break;
5249 }
5250 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: {
5251 PendingTypeCheckedLoadConstVCalls.push_back(
5252 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5253 break;
5254 }
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005255 case bitc::FS_CFI_FUNCTION_DEFS: {
5256 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5257 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005258 CfiFunctionDefs.insert(
5259 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005260 break;
5261 }
5262 case bitc::FS_CFI_FUNCTION_DECLS: {
5263 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5264 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005265 CfiFunctionDecls.insert(
5266 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005267 break;
5268 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005269 }
5270 }
5271 llvm_unreachable("Exit infinite loop");
5272}
5273
5274// Parse the module string table block into the Index.
5275// This populates the ModulePathStringTable map in the index.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005276Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005277 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5278 return error("Invalid record");
5279
5280 SmallVector<uint64_t, 64> Record;
5281
5282 SmallString<128> ModulePath;
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005283 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005284
5285 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005286 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5287
5288 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005289 case BitstreamEntry::SubBlock: // Handled for us already.
5290 case BitstreamEntry::Error:
5291 return error("Malformed block");
5292 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005293 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005294 case BitstreamEntry::Record:
5295 // The interesting case.
5296 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005297 }
5298
5299 Record.clear();
5300 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005301 default: // Default behavior: ignore.
5302 break;
5303 case bitc::MST_CODE_ENTRY: {
5304 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005305 uint64_t ModuleId = Record[0];
5306
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005307 if (convertToString(Record, 1, ModulePath))
5308 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005309
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005310 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5311 ModuleIdMap[ModuleId] = LastSeenModule->first();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005312
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005313 ModulePath.clear();
5314 break;
5315 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005316 /// MST_CODE_HASH: [5*i32]
5317 case bitc::MST_CODE_HASH: {
5318 if (Record.size() != 5)
5319 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005320 if (!LastSeenModule)
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005321 return error("Invalid hash that does not follow a module path");
5322 int Pos = 0;
5323 for (auto &Val : Record) {
5324 assert(!(Val >> 32) && "Unexpected high bits set");
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005325 LastSeenModule->second.second[Pos++] = Val;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005326 }
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005327 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5328 LastSeenModule = nullptr;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005329 break;
5330 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005331 }
5332 }
5333 llvm_unreachable("Exit infinite loop");
5334}
5335
Rafael Espindola48da4f42013-11-04 16:16:24 +00005336namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +00005337
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00005338// FIXME: This class is only here to support the transition to llvm::Error. It
5339// will be removed once this transition is complete. Clients should prefer to
5340// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00005341class BitcodeErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +00005342 const char *name() const noexcept override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00005343 return "llvm.bitcode";
5344 }
Craig Topper73156022014-03-02 09:09:27 +00005345 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005346 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005347 switch (E) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005348 case BitcodeError::CorruptedBitcode:
5349 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00005350 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00005351 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00005352 }
5353};
Eugene Zelenko1804a772016-08-25 00:45:04 +00005354
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00005355} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00005356
Chris Bieneman770163e2014-09-19 20:29:02 +00005357static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5358
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005359const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00005360 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005361}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005362
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005363static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5364 unsigned Block, unsigned RecordID) {
5365 if (Stream.EnterSubBlock(Block))
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005366 return error("Invalid record");
5367
5368 StringRef Strtab;
5369 while (1) {
5370 BitstreamEntry Entry = Stream.advance();
5371 switch (Entry.Kind) {
5372 case BitstreamEntry::EndBlock:
5373 return Strtab;
5374
5375 case BitstreamEntry::Error:
5376 return error("Malformed block");
5377
5378 case BitstreamEntry::SubBlock:
5379 if (Stream.SkipBlock())
5380 return error("Malformed block");
5381 break;
5382
5383 case BitstreamEntry::Record:
5384 StringRef Blob;
5385 SmallVector<uint64_t, 1> Record;
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005386 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005387 Strtab = Blob;
5388 break;
5389 }
5390 }
5391}
5392
Chris Lattner6694f602007-04-29 07:54:31 +00005393//===----------------------------------------------------------------------===//
5394// External interface
5395//===----------------------------------------------------------------------===//
5396
Peter Collingbourne7a748032016-11-16 21:44:45 +00005397Expected<std::vector<BitcodeModule>>
5398llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005399 auto FOrErr = getBitcodeFileContents(Buffer);
5400 if (!FOrErr)
5401 return FOrErr.takeError();
5402 return std::move(FOrErr->Mods);
5403}
5404
5405Expected<BitcodeFileContents>
5406llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005407 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5408 if (!StreamOrErr)
5409 return StreamOrErr.takeError();
5410 BitstreamCursor &Stream = *StreamOrErr;
5411
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005412 BitcodeFileContents F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005413 while (true) {
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005414 uint64_t BCBegin = Stream.getCurrentByteNo();
5415
Peter Collingbourne7a748032016-11-16 21:44:45 +00005416 // We may be consuming bitcode from a client that leaves garbage at the end
5417 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5418 // the end that there cannot possibly be another module, stop looking.
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005419 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005420 return F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005421
5422 BitstreamEntry Entry = Stream.advance();
5423 switch (Entry.Kind) {
5424 case BitstreamEntry::EndBlock:
5425 case BitstreamEntry::Error:
5426 return error("Malformed block");
5427
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005428 case BitstreamEntry::SubBlock: {
5429 uint64_t IdentificationBit = -1ull;
5430 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5431 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5432 if (Stream.SkipBlock())
5433 return error("Malformed block");
5434
5435 Entry = Stream.advance();
5436 if (Entry.Kind != BitstreamEntry::SubBlock ||
5437 Entry.ID != bitc::MODULE_BLOCK_ID)
5438 return error("Malformed block");
5439 }
5440
5441 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5442 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5443 if (Stream.SkipBlock())
5444 return error("Malformed block");
5445
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005446 F.Mods.push_back({Stream.getBitcodeBytes().slice(
5447 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5448 Buffer.getBufferIdentifier(), IdentificationBit,
5449 ModuleBit});
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005450 continue;
5451 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005452
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005453 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005454 Expected<StringRef> Strtab =
5455 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005456 if (!Strtab)
5457 return Strtab.takeError();
5458 // This string table is used by every preceding bitcode module that does
5459 // not have its own string table. A bitcode file may have multiple
5460 // string tables if it was created by binary concatenation, for example
5461 // with "llvm-cat -b".
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005462 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005463 if (!I->Strtab.empty())
5464 break;
5465 I->Strtab = *Strtab;
5466 }
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005467 // Similarly, the string table is used by every preceding symbol table;
5468 // normally there will be just one unless the bitcode file was created
5469 // by binary concatenation.
5470 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5471 F.StrtabForSymtab = *Strtab;
5472 continue;
5473 }
5474
5475 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5476 Expected<StringRef> SymtabOrErr =
5477 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5478 if (!SymtabOrErr)
5479 return SymtabOrErr.takeError();
5480
5481 // We can expect the bitcode file to have multiple symbol tables if it
5482 // was created by binary concatenation. In that case we silently
5483 // ignore any subsequent symbol tables, which is fine because this is a
5484 // low level function. The client is expected to notice that the number
5485 // of modules in the symbol table does not match the number of modules
5486 // in the input file and regenerate the symbol table.
5487 if (F.Symtab.empty())
5488 F.Symtab = *SymtabOrErr;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005489 continue;
5490 }
5491
Peter Collingbourne7a748032016-11-16 21:44:45 +00005492 if (Stream.SkipBlock())
5493 return error("Malformed block");
5494 continue;
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005495 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005496 case BitstreamEntry::Record:
5497 Stream.skipRecord(Entry.ID);
5498 continue;
5499 }
5500 }
5501}
5502
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005503/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00005504///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005505/// This isn't always used in a lazy context. In particular, it's also used by
Peter Collingbourne7a748032016-11-16 21:44:45 +00005506/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005507/// in forward-referenced functions from block address references.
5508///
Rafael Espindola728074b2015-06-17 00:40:56 +00005509/// \param[in] MaterializeAll Set to \c true if we should materialize
5510/// everything.
Peter Collingbourne7a748032016-11-16 21:44:45 +00005511Expected<std::unique_ptr<Module>>
5512BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005513 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005514 BitstreamCursor Stream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005515
Peter Collingbourne7a748032016-11-16 21:44:45 +00005516 std::string ProducerIdentification;
5517 if (IdentificationBit != -1ull) {
5518 Stream.JumpToBit(IdentificationBit);
5519 Expected<std::string> ProducerIdentificationOrErr =
5520 readIdentificationBlock(Stream);
5521 if (!ProducerIdentificationOrErr)
5522 return ProducerIdentificationOrErr.takeError();
5523
5524 ProducerIdentification = *ProducerIdentificationOrErr;
5525 }
5526
5527 Stream.JumpToBit(ModuleBit);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005528 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5529 Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005530
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005531 std::unique_ptr<Module> M =
Peter Collingbourne7a748032016-11-16 21:44:45 +00005532 llvm::make_unique<Module>(ModuleIdentifier, Context);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005533 M->setMaterializer(R);
Rafael Espindolab7993462012-01-02 07:49:53 +00005534
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005535 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005536 if (Error Err =
5537 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
Peter Collingbourned9445c42016-11-13 07:00:17 +00005538 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005539
5540 if (MaterializeAll) {
5541 // Read in the entire module, and destroy the BitcodeReader.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00005542 if (Error Err = M->materializeAll())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005543 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005544 } else {
5545 // Resolve forward references from blockaddresses.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005546 if (Error Err = R->materializeForwardReferencedFunctions())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005547 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005548 }
5549 return std::move(M);
Chris Lattner6694f602007-04-29 07:54:31 +00005550}
5551
Peter Collingbourned9445c42016-11-13 07:00:17 +00005552Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005553BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5554 bool IsImporting) {
5555 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005556}
5557
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005558// Parse the specified bitcode buffer and merge the index into CombinedIndex.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005559// We don't use ModuleIdentifier here because the client may need to control the
5560// module path used in the combined summary (e.g. when reading summaries for
5561// regular LTO modules).
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005562Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005563 StringRef ModulePath, uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005564 BitstreamCursor Stream(Buffer);
5565 Stream.JumpToBit(ModuleBit);
5566
5567 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005568 ModulePath, ModuleId);
Peter Collingbourne440e2042017-05-01 22:48:10 +00005569 return R.parseModule();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005570}
5571
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005572// Parse the specified bitcode buffer, returning the function info index.
5573Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5574 BitstreamCursor Stream(Buffer);
5575 Stream.JumpToBit(ModuleBit);
5576
5577 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005578 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5579 ModuleIdentifier, 0);
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005580
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005581 if (Error Err = R.parseModule())
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005582 return std::move(Err);
5583
5584 return std::move(Index);
5585}
5586
5587// Check if the given bitcode buffer contains a global value summary block.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005588Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005589 BitstreamCursor Stream(Buffer);
5590 Stream.JumpToBit(ModuleBit);
5591
5592 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5593 return error("Invalid record");
5594
5595 while (true) {
5596 BitstreamEntry Entry = Stream.advance();
5597
5598 switch (Entry.Kind) {
5599 case BitstreamEntry::Error:
5600 return error("Malformed block");
5601 case BitstreamEntry::EndBlock:
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005602 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false};
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005603
5604 case BitstreamEntry::SubBlock:
5605 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005606 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true};
5607
5608 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID)
5609 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true};
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005610
5611 // Ignore other sub-blocks.
5612 if (Stream.SkipBlock())
5613 return error("Malformed block");
5614 continue;
5615
5616 case BitstreamEntry::Record:
5617 Stream.skipRecord(Entry.ID);
5618 continue;
5619 }
5620 }
5621}
5622
5623static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005624 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5625 if (!MsOrErr)
5626 return MsOrErr.takeError();
5627
5628 if (MsOrErr->size() != 1)
5629 return error("Expected a single module");
5630
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005631 return (*MsOrErr)[0];
5632}
5633
5634Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005635llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5636 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005637 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5638 if (!BM)
5639 return BM.takeError();
5640
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005641 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005642}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005643
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005644Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5645 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5646 bool ShouldLazyLoadMetadata, bool IsImporting) {
5647 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5648 IsImporting);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005649 if (MOrErr)
5650 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5651 return MOrErr;
5652}
5653
Peter Collingbourne7a748032016-11-16 21:44:45 +00005654Expected<std::unique_ptr<Module>>
5655BitcodeModule::parseModule(LLVMContext &Context) {
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005656 return getModuleImpl(Context, true, false, false);
Chad Rosierca2567b2011-12-07 21:44:12 +00005657 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5658 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00005659}
Bill Wendling0198ce02010-10-06 01:22:42 +00005660
Peter Collingbourne7a748032016-11-16 21:44:45 +00005661Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5662 LLVMContext &Context) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005663 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5664 if (!BM)
5665 return BM.takeError();
Peter Collingbourne7a748032016-11-16 21:44:45 +00005666
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005667 return BM->parseModule(Context);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005668}
5669
Peter Collingbournecd513a42016-11-11 19:50:24 +00005670Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5671 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005672 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005673 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005674
Peter Collingbournecd513a42016-11-11 19:50:24 +00005675 return readTriple(*StreamOrErr);
Bill Wendling0198ce02010-10-06 01:22:42 +00005676}
Teresa Johnson403a7872015-10-04 14:33:43 +00005677
Peter Collingbournecd513a42016-11-11 19:50:24 +00005678Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5679 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005680 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005681 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005682
Peter Collingbournecd513a42016-11-11 19:50:24 +00005683 return hasObjCCategory(*StreamOrErr);
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00005684}
5685
Peter Collingbournecd513a42016-11-11 19:50:24 +00005686Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5687 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005688 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005689 return StreamOrErr.takeError();
5690
5691 return readIdentificationCode(*StreamOrErr);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00005692}
5693
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005694Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
5695 ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005696 uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005697 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5698 if (!BM)
5699 return BM.takeError();
5700
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005701 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005702}
5703
Peter Collingbourne6de481a2016-11-11 19:50:39 +00005704Expected<std::unique_ptr<ModuleSummaryIndex>>
5705llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005706 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5707 if (!BM)
5708 return BM.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005709
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005710 return BM->getSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00005711}
5712
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005713Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005714 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5715 if (!BM)
5716 return BM.takeError();
Teresa Johnson403a7872015-10-04 14:33:43 +00005717
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005718 return BM->getLTOInfo();
Teresa Johnson403a7872015-10-04 14:33:43 +00005719}
Peter Collingbournec15d60b2017-05-01 20:42:32 +00005720
5721Expected<std::unique_ptr<ModuleSummaryIndex>>
Teresa Johnson4cd12ce2017-05-12 19:32:11 +00005722llvm::getModuleSummaryIndexForFile(StringRef Path,
5723 bool IgnoreEmptyThinLTOIndexFile) {
Peter Collingbournec15d60b2017-05-01 20:42:32 +00005724 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5725 MemoryBuffer::getFileOrSTDIN(Path);
5726 if (!FileOrErr)
5727 return errorCodeToError(FileOrErr.getError());
5728 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5729 return nullptr;
5730 return getModuleSummaryIndex(**FileOrErr);
5731}