blob: c45e9645adc0e94dea663f43eaaf0a0975b809a2 [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
Chris Lattner6694f602007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner1314b992007-04-22 06:23:29 +000011#include "BitcodeReader.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
David Majnemer3087b222015-01-20 05:58:07 +000014#include "llvm/ADT/Triple.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000015#include "llvm/Bitcode/LLVMBitCodes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000016#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000018#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DerivedTypes.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000020#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/InlineAsm.h"
22#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000023#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
25#include "llvm/IR/OperandTraits.h"
26#include "llvm/IR/Operator.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000027#include "llvm/Support/DataStream.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000028#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000029#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000030#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000031#include "llvm/Support/raw_ostream.h"
Chris Bieneman770163e2014-09-19 20:29:02 +000032
Chris Lattner1314b992007-04-22 06:23:29 +000033using namespace llvm;
34
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000035enum {
36 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
37};
38
Rafael Espindolad0b23be2015-01-10 00:07:30 +000039BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
40 DiagnosticSeverity Severity,
41 const Twine &Msg)
42 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
43
44void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
45
46static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
47 std::error_code EC, const Twine &Message) {
48 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
49 DiagnosticHandler(DI);
50 return EC;
51}
52
53static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
54 std::error_code EC) {
55 return Error(DiagnosticHandler, EC, EC.message());
56}
57
58std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
59 return ::Error(DiagnosticHandler, make_error_code(E), Message);
60}
61
62std::error_code BitcodeReader::Error(const Twine &Message) {
63 return ::Error(DiagnosticHandler,
64 make_error_code(BitcodeError::CorruptedBitcode), Message);
65}
66
67std::error_code BitcodeReader::Error(BitcodeError E) {
68 return ::Error(DiagnosticHandler, make_error_code(E));
69}
70
71static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
72 LLVMContext &C) {
73 if (F)
74 return F;
75 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
76}
77
78BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
79 DiagnosticHandlerFunction DiagnosticHandler)
80 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
81 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
82 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
83 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
84 WillMaterializeAllForwardRefs(false) {}
85
86BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
87 DiagnosticHandlerFunction DiagnosticHandler)
88 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
89 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
90 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
91 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
92 WillMaterializeAllForwardRefs(false) {}
93
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000094std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
95 if (WillMaterializeAllForwardRefs)
96 return std::error_code();
97
98 // Prevent recursion.
99 WillMaterializeAllForwardRefs = true;
100
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000101 while (!BasicBlockFwdRefQueue.empty()) {
102 Function *F = BasicBlockFwdRefQueue.front();
103 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000104 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000105 if (!BasicBlockFwdRefs.count(F))
106 // Already materialized.
107 continue;
108
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000109 // Check for a function that isn't materializable to prevent an infinite
110 // loop. When parsing a blockaddress stored in a global variable, there
111 // isn't a trivial way to check if a function will have a body without a
112 // linear search through FunctionsWithBodies, so just check it here.
113 if (!F->isMaterializable())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000114 return Error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000115
116 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000117 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000118 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000119 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000120 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000121
122 // Reset state.
123 WillMaterializeAllForwardRefs = false;
124 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000125}
126
Chris Lattner9eeada92007-05-18 04:02:46 +0000127void BitcodeReader::FreeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000128 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000129 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000130 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +0000131 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000132 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000133
Bill Wendlinge94d8432012-12-07 23:16:57 +0000134 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000135 std::vector<BasicBlock*>().swap(FunctionBBs);
136 std::vector<Function*>().swap(FunctionsWithBodies);
137 DeferredFunctionInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000138 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000139
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000140 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000141 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000142}
143
Chris Lattnerfee5a372007-05-04 03:30:17 +0000144//===----------------------------------------------------------------------===//
145// Helper functions to implement forward reference resolution, etc.
146//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000147
Chris Lattner1314b992007-04-22 06:23:29 +0000148/// ConvertToString - Convert a string from a record into an std::string, return
149/// true on failure.
Chris Lattnerccaa4482007-04-23 21:26:05 +0000150template<typename StrTy>
Benjamin Kramer9704ed02012-05-28 14:10:31 +0000151static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000152 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000153 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000154 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000155
Chris Lattnere14cb882007-05-04 19:11:41 +0000156 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
157 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000158 return false;
159}
160
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000161static bool hasImplicitComdat(size_t Val) {
162 switch (Val) {
163 default:
164 return false;
165 case 1: // Old WeakAnyLinkage
166 case 4: // Old LinkOnceAnyLinkage
167 case 10: // Old WeakODRLinkage
168 case 11: // Old LinkOnceODRLinkage
169 return true;
170 }
171}
172
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000173static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000174 switch (Val) {
175 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000176 case 0:
177 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000178 case 2:
179 return GlobalValue::AppendingLinkage;
180 case 3:
181 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000182 case 5:
183 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
184 case 6:
185 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
186 case 7:
187 return GlobalValue::ExternalWeakLinkage;
188 case 8:
189 return GlobalValue::CommonLinkage;
190 case 9:
191 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000192 case 12:
193 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000194 case 13:
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
196 case 14:
197 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000198 case 15:
199 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000200 case 1: // Old value with implicit comdat.
201 case 16:
202 return GlobalValue::WeakAnyLinkage;
203 case 10: // Old value with implicit comdat.
204 case 17:
205 return GlobalValue::WeakODRLinkage;
206 case 4: // Old value with implicit comdat.
207 case 18:
208 return GlobalValue::LinkOnceAnyLinkage;
209 case 11: // Old value with implicit comdat.
210 case 19:
211 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000212 }
213}
214
215static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
216 switch (Val) {
217 default: // Map unknown visibilities to default.
218 case 0: return GlobalValue::DefaultVisibility;
219 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000220 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000221 }
222}
223
Nico Rieck7157bb72014-01-14 15:22:47 +0000224static GlobalValue::DLLStorageClassTypes
225GetDecodedDLLStorageClass(unsigned Val) {
226 switch (Val) {
227 default: // Map unknown values to default.
228 case 0: return GlobalValue::DefaultStorageClass;
229 case 1: return GlobalValue::DLLImportStorageClass;
230 case 2: return GlobalValue::DLLExportStorageClass;
231 }
232}
233
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000234static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
235 switch (Val) {
236 case 0: return GlobalVariable::NotThreadLocal;
237 default: // Map unknown non-zero value to general dynamic.
238 case 1: return GlobalVariable::GeneralDynamicTLSModel;
239 case 2: return GlobalVariable::LocalDynamicTLSModel;
240 case 3: return GlobalVariable::InitialExecTLSModel;
241 case 4: return GlobalVariable::LocalExecTLSModel;
242 }
243}
244
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000245static int GetDecodedCastOpcode(unsigned Val) {
246 switch (Val) {
247 default: return -1;
248 case bitc::CAST_TRUNC : return Instruction::Trunc;
249 case bitc::CAST_ZEXT : return Instruction::ZExt;
250 case bitc::CAST_SEXT : return Instruction::SExt;
251 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
252 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
253 case bitc::CAST_UITOFP : return Instruction::UIToFP;
254 case bitc::CAST_SITOFP : return Instruction::SIToFP;
255 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
256 case bitc::CAST_FPEXT : return Instruction::FPExt;
257 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
258 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
259 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000260 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000261 }
262}
Chris Lattner229907c2011-07-18 04:54:35 +0000263static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000264 switch (Val) {
265 default: return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000266 case bitc::BINOP_ADD:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000267 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000268 case bitc::BINOP_SUB:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000269 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000270 case bitc::BINOP_MUL:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000271 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000272 case bitc::BINOP_UDIV: return Instruction::UDiv;
273 case bitc::BINOP_SDIV:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000274 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000275 case bitc::BINOP_UREM: return Instruction::URem;
276 case bitc::BINOP_SREM:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000277 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000278 case bitc::BINOP_SHL: return Instruction::Shl;
279 case bitc::BINOP_LSHR: return Instruction::LShr;
280 case bitc::BINOP_ASHR: return Instruction::AShr;
281 case bitc::BINOP_AND: return Instruction::And;
282 case bitc::BINOP_OR: return Instruction::Or;
283 case bitc::BINOP_XOR: return Instruction::Xor;
284 }
285}
286
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000287static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
288 switch (Val) {
289 default: return AtomicRMWInst::BAD_BINOP;
290 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
291 case bitc::RMW_ADD: return AtomicRMWInst::Add;
292 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
293 case bitc::RMW_AND: return AtomicRMWInst::And;
294 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
295 case bitc::RMW_OR: return AtomicRMWInst::Or;
296 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
297 case bitc::RMW_MAX: return AtomicRMWInst::Max;
298 case bitc::RMW_MIN: return AtomicRMWInst::Min;
299 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
300 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
301 }
302}
303
Eli Friedmanfee02c62011-07-25 23:16:38 +0000304static AtomicOrdering GetDecodedOrdering(unsigned Val) {
305 switch (Val) {
306 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
307 case bitc::ORDERING_UNORDERED: return Unordered;
308 case bitc::ORDERING_MONOTONIC: return Monotonic;
309 case bitc::ORDERING_ACQUIRE: return Acquire;
310 case bitc::ORDERING_RELEASE: return Release;
311 case bitc::ORDERING_ACQREL: return AcquireRelease;
312 default: // Map unknown orderings to sequentially-consistent.
313 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
314 }
315}
316
317static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
318 switch (Val) {
319 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
320 default: // Map unknown scopes to cross-thread.
321 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
322 }
323}
324
David Majnemerdad0a642014-06-27 18:19:56 +0000325static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
326 switch (Val) {
327 default: // Map unknown selection kinds to any.
328 case bitc::COMDAT_SELECTION_KIND_ANY:
329 return Comdat::Any;
330 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
331 return Comdat::ExactMatch;
332 case bitc::COMDAT_SELECTION_KIND_LARGEST:
333 return Comdat::Largest;
334 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
335 return Comdat::NoDuplicates;
336 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
337 return Comdat::SameSize;
338 }
339}
340
Nico Rieck7157bb72014-01-14 15:22:47 +0000341static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
342 switch (Val) {
343 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
344 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
345 }
346}
347
Gabor Greiff6caff662008-05-10 08:32:32 +0000348namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000349namespace {
350 /// @brief A class for maintaining the slot number definition
351 /// as a placeholder for the actual definition for forward constants defs.
352 class ConstantPlaceHolder : public ConstantExpr {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000353 void operator=(const ConstantPlaceHolder &) = delete;
Gabor Greife9ecc682008-04-06 20:25:17 +0000354 public:
355 // allocate space for exactly one operand
356 void *operator new(size_t s) {
357 return User::operator new(s, 1);
358 }
Chris Lattner229907c2011-07-18 04:54:35 +0000359 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000360 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000361 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner1663cca2007-04-24 05:48:56 +0000362 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000363
Chris Lattner74429932008-08-21 02:34:16 +0000364 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner74429932008-08-21 02:34:16 +0000365 static bool classof(const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366 return isa<ConstantExpr>(V) &&
Chris Lattner74429932008-08-21 02:34:16 +0000367 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
368 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000369
370
Gabor Greiff6caff662008-05-10 08:32:32 +0000371 /// Provide fast operand accessors
Richard Trieue3d126c2014-11-21 02:42:08 +0000372 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner1663cca2007-04-24 05:48:56 +0000373 };
374}
375
Chris Lattner2d8cd802009-03-31 22:55:09 +0000376// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000377template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000378struct OperandTraits<ConstantPlaceHolder> :
379 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000380};
Richard Trieue3d126c2014-11-21 02:42:08 +0000381DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Gabor Greiff6caff662008-05-10 08:32:32 +0000382}
383
Chris Lattner2d8cd802009-03-31 22:55:09 +0000384
385void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
386 if (Idx == size()) {
387 push_back(V);
388 return;
389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000390
Chris Lattner2d8cd802009-03-31 22:55:09 +0000391 if (Idx >= size())
392 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000393
Chris Lattner2d8cd802009-03-31 22:55:09 +0000394 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000395 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000396 OldV = V;
397 return;
398 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000399
Chris Lattner2d8cd802009-03-31 22:55:09 +0000400 // Handle constants and non-constants (e.g. instrs) differently for
401 // efficiency.
402 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
403 ResolveConstants.push_back(std::make_pair(PHC, Idx));
404 OldV = V;
405 } else {
406 // If there was a forward reference to this value, replace it.
407 Value *PrevVal = OldV;
408 OldV->replaceAllUsesWith(V);
409 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000410 }
411}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000412
Gabor Greiff6caff662008-05-10 08:32:32 +0000413
Chris Lattner1663cca2007-04-24 05:48:56 +0000414Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000415 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000416 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000417 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000418
Chris Lattner2d8cd802009-03-31 22:55:09 +0000419 if (Value *V = ValuePtrs[Idx]) {
Chris Lattner83930552007-05-01 07:01:57 +0000420 assert(Ty == V->getType() && "Type mismatch in constant table!");
421 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000422 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000423
424 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000425 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000426 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000427 return C;
428}
429
Chris Lattner229907c2011-07-18 04:54:35 +0000430Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000431 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000432 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000433
Chris Lattner2d8cd802009-03-31 22:55:09 +0000434 if (Value *V = ValuePtrs[Idx]) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000435 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
Chris Lattner83930552007-05-01 07:01:57 +0000436 return V;
437 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000438
Chris Lattner1fc27f02007-05-02 05:16:49 +0000439 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000440 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000441
Chris Lattner83930552007-05-01 07:01:57 +0000442 // Create and return a placeholder, which will later be RAUW'd.
443 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000444 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000445 return V;
446}
447
Chris Lattner74429932008-08-21 02:34:16 +0000448/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
449/// resolves any forward references. The idea behind this is that we sometimes
450/// get constants (such as large arrays) which reference *many* forward ref
451/// constants. Replacing each of these causes a lot of thrashing when
452/// building/reuniquing the constant. Instead of doing this, we look at all the
453/// uses and rewrite all the place holders at once for any constant that uses
454/// a placeholder.
455void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000456 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000457 // binary search.
458 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000459
Chris Lattner74429932008-08-21 02:34:16 +0000460 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000461
Chris Lattner74429932008-08-21 02:34:16 +0000462 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000463 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000464 Constant *Placeholder = ResolveConstants.back().first;
465 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000466
Chris Lattner74429932008-08-21 02:34:16 +0000467 // Loop over all users of the placeholder, updating them to reference the
468 // new value. If they reference more than one placeholder, update them all
469 // at once.
470 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000471 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000472 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000473
Chris Lattner74429932008-08-21 02:34:16 +0000474 // If the using object isn't uniqued, just update the operands. This
475 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000476 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000477 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000478 continue;
479 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000480
Chris Lattner74429932008-08-21 02:34:16 +0000481 // Otherwise, we have a constant that uses the placeholder. Replace that
482 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000483 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000484 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
485 I != E; ++I) {
486 Value *NewOp;
487 if (!isa<ConstantPlaceHolder>(*I)) {
488 // Not a placeholder reference.
489 NewOp = *I;
490 } else if (*I == Placeholder) {
491 // Common case is that it just references this one placeholder.
492 NewOp = RealVal;
493 } else {
494 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000495 ResolveConstantsTy::iterator It =
496 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000497 std::pair<Constant*, unsigned>(cast<Constant>(*I),
498 0));
499 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000500 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000501 }
502
503 NewOps.push_back(cast<Constant>(NewOp));
504 }
505
506 // Make the new constant.
507 Constant *NewC;
508 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000509 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000510 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000511 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000512 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000513 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000514 } else {
515 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000516 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000517 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000518
Chris Lattner74429932008-08-21 02:34:16 +0000519 UserC->replaceAllUsesWith(NewC);
520 UserC->destroyConstant();
521 NewOps.clear();
522 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000523
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000524 // Update all ValueHandles, they should be the only users at this point.
525 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000526 delete Placeholder;
527 }
528}
529
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000530void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000531 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000532 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000533 return;
534 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000535
Devang Patel05eb6172009-08-04 06:00:18 +0000536 if (Idx >= size())
537 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000538
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000539 TrackingMDRef &OldMD = MDValuePtrs[Idx];
540 if (!OldMD) {
541 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000542 return;
543 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000544
Devang Patel05eb6172009-08-04 06:00:18 +0000545 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000546 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000547 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000548 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +0000549}
550
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000551Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000552 if (Idx >= size())
553 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000554
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000555 if (Metadata *MD = MDValuePtrs[Idx])
556 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000557
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000558 // Track forward refs to be resolved later.
559 if (AnyFwdRefs) {
560 MinFwdRef = std::min(MinFwdRef, Idx);
561 MaxFwdRef = std::max(MaxFwdRef, Idx);
562 } else {
563 AnyFwdRefs = true;
564 MinFwdRef = MaxFwdRef = Idx;
565 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000566 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000567
568 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000569 Metadata *MD = MDNode::getTemporary(Context, None).release();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000570 MDValuePtrs[Idx].reset(MD);
571 return MD;
572}
573
574void BitcodeReaderMDValueList::tryToResolveCycles() {
575 if (!AnyFwdRefs)
576 // Nothing to do.
577 return;
578
579 if (NumFwdRefs)
580 // Still forward references... can't resolve cycles.
581 return;
582
583 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000584 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
585 auto &MD = MDValuePtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000586 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000587 if (!N)
588 continue;
589
590 assert(!N->isTemporary() && "Unexpected forward reference");
591 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000592 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000593
594 // Make sure we return early again until there's another forward ref.
595 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +0000596}
Chris Lattner1314b992007-04-22 06:23:29 +0000597
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000598Type *BitcodeReader::getTypeByID(unsigned ID) {
599 // The type table size is always specified correctly.
600 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +0000601 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +0000602
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000603 if (Type *Ty = TypeList[ID])
604 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000605
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000606 // If we have a forward reference, the only possible case is when it is to a
607 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000608 return TypeList[ID] = createIdentifiedStructType(Context);
609}
610
611StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
612 StringRef Name) {
613 auto *Ret = StructType::create(Context, Name);
614 IdentifiedStructTypes.push_back(Ret);
615 return Ret;
616}
617
618StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
619 auto *Ret = StructType::create(Context);
620 IdentifiedStructTypes.push_back(Ret);
621 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +0000622}
623
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000624
Chris Lattnerfee5a372007-05-04 03:30:17 +0000625//===----------------------------------------------------------------------===//
626// Functions for parsing blocks from the bitcode file
627//===----------------------------------------------------------------------===//
628
Bill Wendling56aeccc2013-02-04 23:32:23 +0000629
630/// \brief This fills an AttrBuilder object with the LLVM attributes that have
631/// been decoded from the given integer. This function must stay in sync with
632/// 'encodeLLVMAttributesForBitcode'.
633static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
634 uint64_t EncodedAttrs) {
635 // FIXME: Remove in 4.0.
636
637 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
638 // the bits above 31 down by 11 bits.
639 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
640 assert((!Alignment || isPowerOf2_32(Alignment)) &&
641 "Alignment must be a power of two.");
642
643 if (Alignment)
644 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +0000645 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +0000646 (EncodedAttrs & 0xffff));
647}
648
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000649std::error_code BitcodeReader::ParseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +0000650 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000651 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000652
Devang Patela05633e2008-09-26 22:53:05 +0000653 if (!MAttributes.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000654 return Error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000655
Chris Lattnerfee5a372007-05-04 03:30:17 +0000656 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000657
Bill Wendling71173cb2013-01-27 00:36:48 +0000658 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000659
Chris Lattnerfee5a372007-05-04 03:30:17 +0000660 // Read all the records.
661 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000662 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000663
Chris Lattner27d38752013-01-20 02:13:19 +0000664 switch (Entry.Kind) {
665 case BitstreamEntry::SubBlock: // Handled for us already.
666 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000667 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +0000668 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000669 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000670 case BitstreamEntry::Record:
671 // The interesting case.
672 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +0000673 }
Joe Abbey97b7a172013-02-06 22:14:06 +0000674
Chris Lattnerfee5a372007-05-04 03:30:17 +0000675 // Read a record.
676 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +0000677 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +0000678 default: // Default behavior: ignore.
679 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000680 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
681 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +0000682 if (Record.size() & 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000683 return Error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +0000684
Chris Lattnerfee5a372007-05-04 03:30:17 +0000685 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +0000686 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000687 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +0000688 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +0000689 }
Devang Patela05633e2008-09-26 22:53:05 +0000690
Bill Wendlinge94d8432012-12-07 23:16:57 +0000691 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +0000692 Attrs.clear();
693 break;
694 }
Bill Wendling0dc08912013-02-12 08:13:50 +0000695 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
696 for (unsigned i = 0, e = Record.size(); i != e; ++i)
697 Attrs.push_back(MAttributeGroups[Record[i]]);
698
699 MAttributes.push_back(AttributeSet::get(Context, Attrs));
700 Attrs.clear();
701 break;
702 }
Duncan Sands04eb67e2007-11-20 14:09:29 +0000703 }
Chris Lattnerfee5a372007-05-04 03:30:17 +0000704 }
705}
706
Reid Klecknere9f36af2013-11-12 01:31:00 +0000707// Returns Attribute::None on unrecognized codes.
708static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
709 switch (Code) {
710 default:
711 return Attribute::None;
712 case bitc::ATTR_KIND_ALIGNMENT:
713 return Attribute::Alignment;
714 case bitc::ATTR_KIND_ALWAYS_INLINE:
715 return Attribute::AlwaysInline;
716 case bitc::ATTR_KIND_BUILTIN:
717 return Attribute::Builtin;
718 case bitc::ATTR_KIND_BY_VAL:
719 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +0000720 case bitc::ATTR_KIND_IN_ALLOCA:
721 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000722 case bitc::ATTR_KIND_COLD:
723 return Attribute::Cold;
724 case bitc::ATTR_KIND_INLINE_HINT:
725 return Attribute::InlineHint;
726 case bitc::ATTR_KIND_IN_REG:
727 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000728 case bitc::ATTR_KIND_JUMP_TABLE:
729 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000730 case bitc::ATTR_KIND_MIN_SIZE:
731 return Attribute::MinSize;
732 case bitc::ATTR_KIND_NAKED:
733 return Attribute::Naked;
734 case bitc::ATTR_KIND_NEST:
735 return Attribute::Nest;
736 case bitc::ATTR_KIND_NO_ALIAS:
737 return Attribute::NoAlias;
738 case bitc::ATTR_KIND_NO_BUILTIN:
739 return Attribute::NoBuiltin;
740 case bitc::ATTR_KIND_NO_CAPTURE:
741 return Attribute::NoCapture;
742 case bitc::ATTR_KIND_NO_DUPLICATE:
743 return Attribute::NoDuplicate;
744 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
745 return Attribute::NoImplicitFloat;
746 case bitc::ATTR_KIND_NO_INLINE:
747 return Attribute::NoInline;
748 case bitc::ATTR_KIND_NON_LAZY_BIND:
749 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000750 case bitc::ATTR_KIND_NON_NULL:
751 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000752 case bitc::ATTR_KIND_DEREFERENCEABLE:
753 return Attribute::Dereferenceable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000754 case bitc::ATTR_KIND_NO_RED_ZONE:
755 return Attribute::NoRedZone;
756 case bitc::ATTR_KIND_NO_RETURN:
757 return Attribute::NoReturn;
758 case bitc::ATTR_KIND_NO_UNWIND:
759 return Attribute::NoUnwind;
760 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
761 return Attribute::OptimizeForSize;
762 case bitc::ATTR_KIND_OPTIMIZE_NONE:
763 return Attribute::OptimizeNone;
764 case bitc::ATTR_KIND_READ_NONE:
765 return Attribute::ReadNone;
766 case bitc::ATTR_KIND_READ_ONLY:
767 return Attribute::ReadOnly;
768 case bitc::ATTR_KIND_RETURNED:
769 return Attribute::Returned;
770 case bitc::ATTR_KIND_RETURNS_TWICE:
771 return Attribute::ReturnsTwice;
772 case bitc::ATTR_KIND_S_EXT:
773 return Attribute::SExt;
774 case bitc::ATTR_KIND_STACK_ALIGNMENT:
775 return Attribute::StackAlignment;
776 case bitc::ATTR_KIND_STACK_PROTECT:
777 return Attribute::StackProtect;
778 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
779 return Attribute::StackProtectReq;
780 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
781 return Attribute::StackProtectStrong;
782 case bitc::ATTR_KIND_STRUCT_RET:
783 return Attribute::StructRet;
784 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
785 return Attribute::SanitizeAddress;
786 case bitc::ATTR_KIND_SANITIZE_THREAD:
787 return Attribute::SanitizeThread;
788 case bitc::ATTR_KIND_SANITIZE_MEMORY:
789 return Attribute::SanitizeMemory;
790 case bitc::ATTR_KIND_UW_TABLE:
791 return Attribute::UWTable;
792 case bitc::ATTR_KIND_Z_EXT:
793 return Attribute::ZExt;
794 }
795}
796
JF Bastien30bf96b2015-02-22 19:32:03 +0000797std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
798 unsigned &Alignment) {
799 // Note: Alignment in bitcode files is incremented by 1, so that zero
800 // can be used for default alignment.
801 if (Exponent > Value::MaxAlignmentExponent + 1)
802 return Error("Invalid alignment value");
803 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
804 return std::error_code();
805}
806
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000807std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
808 Attribute::AttrKind *Kind) {
Reid Klecknere9f36af2013-11-12 01:31:00 +0000809 *Kind = GetAttrFromCode(Code);
810 if (*Kind == Attribute::None)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000811 return Error(BitcodeError::CorruptedBitcode,
812 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000813 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000814}
815
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000816std::error_code BitcodeReader::ParseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +0000817 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000818 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +0000819
820 if (!MAttributeGroups.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000821 return Error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +0000822
823 SmallVector<uint64_t, 64> Record;
824
825 // Read all the records.
826 while (1) {
827 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
828
829 switch (Entry.Kind) {
830 case BitstreamEntry::SubBlock: // Handled for us already.
831 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000832 return Error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +0000833 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000834 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +0000835 case BitstreamEntry::Record:
836 // The interesting case.
837 break;
838 }
839
840 // Read a record.
841 Record.clear();
842 switch (Stream.readRecord(Entry.ID, Record)) {
843 default: // Default behavior: ignore.
844 break;
845 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
846 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000847 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +0000848
Bill Wendlinge46707e2013-02-11 22:32:29 +0000849 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +0000850 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
851
852 AttrBuilder B;
853 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
854 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000855 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000856 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000857 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000858
859 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +0000860 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000861 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000862 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000863 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000864 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000865 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000866 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000867 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000868 else if (Kind == Attribute::Dereferenceable)
869 B.addDereferenceableAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +0000870 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +0000871 assert((Record[i] == 3 || Record[i] == 4) &&
872 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +0000873 bool HasValue = (Record[i++] == 4);
874 SmallString<64> KindStr;
875 SmallString<64> ValStr;
876
877 while (Record[i] != 0 && i != e)
878 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000879 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000880
881 if (HasValue) {
882 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +0000883 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +0000884 while (Record[i] != 0 && i != e)
885 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000886 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000887 }
888
889 B.addAttribute(KindStr.str(), ValStr.str());
890 }
891 }
892
Bill Wendlinge46707e2013-02-11 22:32:29 +0000893 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +0000894 break;
895 }
896 }
897 }
898}
899
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000900std::error_code BitcodeReader::ParseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000901 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000902 return Error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +0000903
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000904 return ParseTypeTableBody();
905}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000907std::error_code BitcodeReader::ParseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +0000908 if (!TypeList.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000909 return Error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +0000910
911 SmallVector<uint64_t, 64> Record;
912 unsigned NumRecords = 0;
913
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000914 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +0000915
Chris Lattner1314b992007-04-22 06:23:29 +0000916 // Read all the records for this type table.
917 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000918 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000919
Chris Lattner27d38752013-01-20 02:13:19 +0000920 switch (Entry.Kind) {
921 case BitstreamEntry::SubBlock: // Handled for us already.
922 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000923 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +0000924 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +0000925 if (NumRecords != TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000926 return Error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000927 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000928 case BitstreamEntry::Record:
929 // The interesting case.
930 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000931 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000932
Chris Lattner1314b992007-04-22 06:23:29 +0000933 // Read a record.
934 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +0000935 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +0000936 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +0000937 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000938 return Error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +0000939 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
940 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
941 // type list. This allows us to reserve space.
942 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000943 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000944 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000945 continue;
Chris Lattner1314b992007-04-22 06:23:29 +0000946 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +0000947 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000948 break;
Dan Gohman518cda42011-12-17 00:04:22 +0000949 case bitc::TYPE_CODE_HALF: // HALF
950 ResultTy = Type::getHalfTy(Context);
951 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000952 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +0000953 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000954 break;
955 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +0000956 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000957 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000958 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +0000959 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000960 break;
961 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000962 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000963 break;
964 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000965 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000966 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000967 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +0000968 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000969 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000970 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +0000971 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000972 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +0000973 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
974 ResultTy = Type::getX86_MMXTy(Context);
975 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +0000976 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +0000977 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000978 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000979
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +0000980 uint64_t NumBits = Record[0];
981 if (NumBits < IntegerType::MIN_INT_BITS ||
982 NumBits > IntegerType::MAX_INT_BITS)
983 return Error("Bitwidth for integer type out of range");
984 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +0000985 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +0000986 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000987 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000988 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +0000989 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000990 return Error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000991 unsigned AddressSpace = 0;
992 if (Record.size() == 2)
993 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000994 ResultTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000995 if (!ResultTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000996 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000997 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +0000998 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000999 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001000 case bitc::TYPE_CODE_FUNCTION_OLD: {
1001 // FIXME: attrid is dead, remove it in LLVM 4.0
1002 // FUNCTION: [vararg, attrid, retty, paramty x N]
1003 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001004 return Error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001005 SmallVector<Type*, 8> ArgTys;
1006 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1007 if (Type *T = getTypeByID(Record[i]))
1008 ArgTys.push_back(T);
1009 else
1010 break;
1011 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001012
Nuno Lopes561dae02012-05-23 15:19:39 +00001013 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001014 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001015 return Error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001016
1017 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1018 break;
1019 }
Chad Rosier95898722011-11-03 00:14:01 +00001020 case bitc::TYPE_CODE_FUNCTION: {
1021 // FUNCTION: [vararg, retty, paramty x N]
1022 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001023 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001024 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001025 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1026 if (Type *T = getTypeByID(Record[i]))
1027 ArgTys.push_back(T);
1028 else
1029 break;
1030 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001031
Chad Rosier95898722011-11-03 00:14:01 +00001032 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001033 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001034 return Error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001035
1036 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1037 break;
1038 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001039 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001040 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001041 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001042 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001043 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1044 if (Type *T = getTypeByID(Record[i]))
1045 EltTys.push_back(T);
1046 else
1047 break;
1048 }
1049 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001050 return Error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001051 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001052 break;
1053 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001054 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1055 if (ConvertToString(Record, 0, TypeName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001056 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001057 continue;
1058
1059 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1060 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001061 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001062
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001063 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001064 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001065
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001066 // Check to see if this was forward referenced, if so fill in the temp.
1067 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1068 if (Res) {
1069 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001070 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001071 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001072 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001073 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001074
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001075 SmallVector<Type*, 8> EltTys;
1076 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1077 if (Type *T = getTypeByID(Record[i]))
1078 EltTys.push_back(T);
1079 else
1080 break;
1081 }
1082 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001083 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001084 Res->setBody(EltTys, Record[0]);
1085 ResultTy = Res;
1086 break;
1087 }
1088 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1089 if (Record.size() != 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001090 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001091
1092 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001093 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001095 // Check to see if this was forward referenced, if so fill in the temp.
1096 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1097 if (Res) {
1098 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001099 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001100 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001101 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001102 TypeName.clear();
1103 ResultTy = Res;
1104 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001105 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001106 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1107 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001108 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001109 if ((ResultTy = getTypeByID(Record[1])))
1110 ResultTy = ArrayType::get(ResultTy, Record[0]);
1111 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001112 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001113 break;
1114 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1115 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001116 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001117 if ((ResultTy = getTypeByID(Record[1])))
1118 ResultTy = VectorType::get(ResultTy, Record[0]);
1119 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001120 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001121 break;
1122 }
1123
1124 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001125 return Error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001126 if (TypeList[NumRecords])
1127 return Error(
1128 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001129 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001130 TypeList[NumRecords++] = ResultTy;
1131 }
1132}
1133
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001134std::error_code BitcodeReader::ParseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001135 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001136 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001137
1138 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001139
David Majnemer3087b222015-01-20 05:58:07 +00001140 Triple TT(TheModule->getTargetTriple());
1141
Chris Lattnerccaa4482007-04-23 21:26:05 +00001142 // Read all the records for this value table.
1143 SmallString<128> ValueName;
1144 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001145 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001146
Chris Lattner27d38752013-01-20 02:13:19 +00001147 switch (Entry.Kind) {
1148 case BitstreamEntry::SubBlock: // Handled for us already.
1149 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001150 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001151 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001152 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001153 case BitstreamEntry::Record:
1154 // The interesting case.
1155 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001156 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001157
Chris Lattnerccaa4482007-04-23 21:26:05 +00001158 // Read a record.
1159 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001160 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001161 default: // Default behavior: unknown type.
1162 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001163 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattnerccaa4482007-04-23 21:26:05 +00001164 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001165 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001166 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001167 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001168 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001169 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001170
Daniel Dunbard786b512009-07-26 00:34:27 +00001171 V->setName(StringRef(ValueName.data(), ValueName.size()));
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001172 if (auto *GO = dyn_cast<GlobalObject>(V)) {
David Majnemer3087b222015-01-20 05:58:07 +00001173 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1174 if (TT.isOSBinFormatMachO())
1175 GO->setComdat(nullptr);
1176 else
1177 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1178 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001179 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001180 ValueName.clear();
1181 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001182 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001183 case bitc::VST_CODE_BBENTRY: {
Chris Lattner6be58c62007-05-03 22:18:21 +00001184 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001185 return Error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001186 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001187 if (!BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001188 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001189
Daniel Dunbard786b512009-07-26 00:34:27 +00001190 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001191 ValueName.clear();
1192 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001193 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001194 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001195 }
1196}
1197
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001198static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1199
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001200std::error_code BitcodeReader::ParseMetadata() {
Devang Patel89923232010-01-11 18:52:33 +00001201 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001202
1203 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001204 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001205
Devang Patel7428d8a2009-07-22 17:43:22 +00001206 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001207
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001208 auto getMD =
1209 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1210 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1211 if (ID)
1212 return getMD(ID - 1);
1213 return nullptr;
1214 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001215 auto getMDString = [&](unsigned ID) -> MDString *{
1216 // This requires that the ID is not really a forward reference. In
1217 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001218 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001219 };
1220
1221#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1222 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1223
Devang Patel7428d8a2009-07-22 17:43:22 +00001224 // Read all the records.
1225 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001226 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001227
Chris Lattner27d38752013-01-20 02:13:19 +00001228 switch (Entry.Kind) {
1229 case BitstreamEntry::SubBlock: // Handled for us already.
1230 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001231 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001232 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001233 MDValueList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001234 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001235 case BitstreamEntry::Record:
1236 // The interesting case.
1237 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001238 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001239
Devang Patel7428d8a2009-07-22 17:43:22 +00001240 // Read a record.
1241 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001242 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001243 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001244 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001245 default: // Default behavior: ignore.
1246 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001247 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001248 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001249 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001250 Record.clear();
1251 Code = Stream.ReadCode();
1252
Chris Lattnerb8778552011-06-17 17:50:30 +00001253 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner27d38752013-01-20 02:13:19 +00001254 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattnerb8778552011-06-17 17:50:30 +00001255 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patel27c87ff2009-07-29 22:34:41 +00001256
1257 // Read named metadata elements.
1258 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001259 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001260 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001261 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001262 if (!MD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001263 return Error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001264 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001265 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001266 break;
1267 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001268 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001269 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001270 // This is a LocalAsMetadata record, the only type of function-local
1271 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001272 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001273 return Error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001274
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001275 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1276 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001277 auto dropRecord = [&] {
1278 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1279 };
1280 if (Record.size() != 2) {
1281 dropRecord();
1282 break;
1283 }
1284
1285 Type *Ty = getTypeByID(Record[0]);
1286 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1287 dropRecord();
1288 break;
1289 }
1290
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001291 MDValueList.AssignValue(
1292 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1293 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001294 break;
1295 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001296 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001297 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001298 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001299 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001300
Devang Patele059ba6e2009-07-23 01:07:34 +00001301 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001302 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001303 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001304 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001305 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001306 return Error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00001307 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001308 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001309 else if (!Ty->isVoidTy()) {
1310 auto *MD =
1311 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1312 assert(isa<ConstantAsMetadata>(MD) &&
1313 "Expected non-function-local metadata");
1314 Elts.push_back(MD);
1315 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00001316 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001317 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001318 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001319 break;
1320 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001321 case bitc::METADATA_VALUE: {
1322 if (Record.size() != 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001323 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001324
1325 Type *Ty = getTypeByID(Record[0]);
1326 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001327 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001328
1329 MDValueList.AssignValue(
1330 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1331 NextMDValueNo++);
1332 break;
1333 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001334 case bitc::METADATA_DISTINCT_NODE:
1335 IsDistinct = true;
1336 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001337 case bitc::METADATA_NODE: {
1338 SmallVector<Metadata *, 8> Elts;
1339 Elts.reserve(Record.size());
1340 for (unsigned ID : Record)
1341 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001342 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1343 : MDNode::get(Context, Elts),
1344 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001345 break;
1346 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001347 case bitc::METADATA_LOCATION: {
1348 if (Record.size() != 5)
1349 return Error("Invalid record");
1350
1351 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1352 unsigned Line = Record[1];
1353 unsigned Column = Record[2];
1354 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1355 Metadata *InlinedAt =
1356 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1357 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1358 NextMDValueNo++);
1359 break;
1360 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001361 case bitc::METADATA_GENERIC_DEBUG: {
1362 if (Record.size() < 4)
1363 return Error("Invalid record");
1364
1365 unsigned Tag = Record[1];
1366 unsigned Version = Record[2];
1367
1368 if (Tag >= 1u << 16 || Version != 0)
1369 return Error("Invalid record");
1370
1371 auto *Header = getMDString(Record[3]);
1372 SmallVector<Metadata *, 8> DwarfOps;
1373 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1374 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1375 : nullptr);
1376 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1377 (Context, Tag, Header, DwarfOps)),
1378 NextMDValueNo++);
1379 break;
1380 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001381 case bitc::METADATA_SUBRANGE: {
1382 if (Record.size() != 3)
1383 return Error("Invalid record");
1384
1385 MDValueList.AssignValue(
1386 GET_OR_DISTINCT(MDSubrange, Record[0],
1387 (Context, Record[1], unrotateSign(Record[2]))),
1388 NextMDValueNo++);
1389 break;
1390 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001391 case bitc::METADATA_ENUMERATOR: {
1392 if (Record.size() != 3)
1393 return Error("Invalid record");
1394
1395 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1396 (Context, unrotateSign(Record[1]),
1397 getMDString(Record[2]))),
1398 NextMDValueNo++);
1399 break;
1400 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001401 case bitc::METADATA_BASIC_TYPE: {
1402 if (Record.size() != 6)
1403 return Error("Invalid record");
1404
1405 MDValueList.AssignValue(
1406 GET_OR_DISTINCT(MDBasicType, Record[0],
1407 (Context, Record[1], getMDString(Record[2]),
1408 Record[3], Record[4], Record[5])),
1409 NextMDValueNo++);
1410 break;
1411 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001412 case bitc::METADATA_DERIVED_TYPE: {
1413 if (Record.size() != 12)
1414 return Error("Invalid record");
1415
1416 MDValueList.AssignValue(
1417 GET_OR_DISTINCT(MDDerivedType, Record[0],
1418 (Context, Record[1], getMDString(Record[2]),
1419 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001420 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1421 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001422 getMDOrNull(Record[11]))),
1423 NextMDValueNo++);
1424 break;
1425 }
1426 case bitc::METADATA_COMPOSITE_TYPE: {
1427 if (Record.size() != 16)
1428 return Error("Invalid record");
1429
1430 MDValueList.AssignValue(
1431 GET_OR_DISTINCT(MDCompositeType, Record[0],
1432 (Context, Record[1], getMDString(Record[2]),
1433 getMDOrNull(Record[3]), Record[4],
1434 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1435 Record[7], Record[8], Record[9], Record[10],
1436 getMDOrNull(Record[11]), Record[12],
1437 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1438 getMDString(Record[15]))),
1439 NextMDValueNo++);
1440 break;
1441 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001442 case bitc::METADATA_SUBROUTINE_TYPE: {
1443 if (Record.size() != 3)
1444 return Error("Invalid record");
1445
1446 MDValueList.AssignValue(
1447 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1448 (Context, Record[1], getMDOrNull(Record[2]))),
1449 NextMDValueNo++);
1450 break;
1451 }
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001452 case bitc::METADATA_FILE: {
1453 if (Record.size() != 3)
1454 return Error("Invalid record");
1455
1456 MDValueList.AssignValue(
1457 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1458 getMDString(Record[2]))),
1459 NextMDValueNo++);
1460 break;
1461 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001462 case bitc::METADATA_COMPILE_UNIT: {
1463 if (Record.size() != 14)
1464 return Error("Invalid record");
1465
1466 MDValueList.AssignValue(
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001467 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1468 (Context, Record[1], getMDOrNull(Record[2]),
1469 getMDString(Record[3]), Record[4],
1470 getMDString(Record[5]), Record[6],
1471 getMDString(Record[7]), Record[8],
1472 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1473 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1474 getMDOrNull(Record[13]))),
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001475 NextMDValueNo++);
1476 break;
1477 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001478 case bitc::METADATA_SUBPROGRAM: {
1479 if (Record.size() != 19)
1480 return Error("Invalid record");
1481
1482 MDValueList.AssignValue(
1483 GET_OR_DISTINCT(
1484 MDSubprogram, Record[0],
1485 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1486 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1487 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1488 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1489 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1490 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1491 NextMDValueNo++);
1492 break;
1493 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001494 case bitc::METADATA_LEXICAL_BLOCK: {
1495 if (Record.size() != 5)
1496 return Error("Invalid record");
1497
1498 MDValueList.AssignValue(
1499 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1500 (Context, getMDOrNull(Record[1]),
1501 getMDOrNull(Record[2]), Record[3], Record[4])),
1502 NextMDValueNo++);
1503 break;
1504 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001505 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1506 if (Record.size() != 4)
1507 return Error("Invalid record");
1508
1509 MDValueList.AssignValue(
1510 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1511 (Context, getMDOrNull(Record[1]),
1512 getMDOrNull(Record[2]), Record[3])),
1513 NextMDValueNo++);
1514 break;
1515 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001516 case bitc::METADATA_NAMESPACE: {
1517 if (Record.size() != 5)
1518 return Error("Invalid record");
1519
1520 MDValueList.AssignValue(
1521 GET_OR_DISTINCT(MDNamespace, Record[0],
1522 (Context, getMDOrNull(Record[1]),
1523 getMDOrNull(Record[2]), getMDString(Record[3]),
1524 Record[4])),
1525 NextMDValueNo++);
1526 break;
1527 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001528 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001529 if (Record.size() != 3)
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001530 return Error("Invalid record");
1531
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001532 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1533 Record[0],
1534 (Context, getMDString(Record[1]),
1535 getMDOrNull(Record[2]))),
1536 NextMDValueNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001537 break;
1538 }
1539 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001540 if (Record.size() != 5)
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001541 return Error("Invalid record");
1542
1543 MDValueList.AssignValue(
1544 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001545 (Context, Record[1], getMDString(Record[2]),
1546 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001547 NextMDValueNo++);
1548 break;
1549 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001550 case bitc::METADATA_GLOBAL_VAR: {
1551 if (Record.size() != 11)
1552 return Error("Invalid record");
1553
1554 MDValueList.AssignValue(
1555 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1556 (Context, getMDOrNull(Record[1]),
1557 getMDString(Record[2]), getMDString(Record[3]),
1558 getMDOrNull(Record[4]), Record[5],
1559 getMDOrNull(Record[6]), Record[7], Record[8],
1560 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1561 NextMDValueNo++);
1562 break;
1563 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001564 case bitc::METADATA_LOCAL_VAR: {
1565 if (Record.size() != 10)
1566 return Error("Invalid record");
1567
1568 MDValueList.AssignValue(
1569 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1570 (Context, Record[1], getMDOrNull(Record[2]),
1571 getMDString(Record[3]), getMDOrNull(Record[4]),
1572 Record[5], getMDOrNull(Record[6]), Record[7],
1573 Record[8], getMDOrNull(Record[9]))),
1574 NextMDValueNo++);
1575 break;
1576 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001577 case bitc::METADATA_EXPRESSION: {
1578 if (Record.size() < 1)
1579 return Error("Invalid record");
1580
1581 MDValueList.AssignValue(
1582 GET_OR_DISTINCT(MDExpression, Record[0],
1583 (Context, makeArrayRef(Record).slice(1))),
1584 NextMDValueNo++);
1585 break;
1586 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001587 case bitc::METADATA_OBJC_PROPERTY: {
1588 if (Record.size() != 8)
1589 return Error("Invalid record");
1590
1591 MDValueList.AssignValue(
1592 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1593 (Context, getMDString(Record[1]),
1594 getMDOrNull(Record[2]), Record[3],
1595 getMDString(Record[4]), getMDString(Record[5]),
1596 Record[6], getMDOrNull(Record[7]))),
1597 NextMDValueNo++);
1598 break;
1599 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001600 case bitc::METADATA_IMPORTED_ENTITY: {
1601 if (Record.size() != 6)
1602 return Error("Invalid record");
1603
1604 MDValueList.AssignValue(
1605 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1606 (Context, Record[1], getMDOrNull(Record[2]),
1607 getMDOrNull(Record[3]), Record[4],
1608 getMDString(Record[5]))),
1609 NextMDValueNo++);
1610 break;
1611 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001612 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00001613 std::string String(Record.begin(), Record.end());
1614 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001615 Metadata *MD = MDString::get(Context, String);
1616 MDValueList.AssignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00001617 break;
1618 }
Devang Patelaf206b82009-09-18 19:26:43 +00001619 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001620 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001621 return Error("Invalid record");
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001622
Devang Patelb1a44772009-09-28 21:14:55 +00001623 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001624 SmallString<8> Name(Record.begin()+1, Record.end());
1625
Chris Lattnera0566972009-12-29 09:01:33 +00001626 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00001627 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001628 return Error("Conflicting METADATA_KIND records");
Devang Patelaf206b82009-09-18 19:26:43 +00001629 break;
1630 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001631 }
1632 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001633#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00001634}
1635
Jan Wen Voungafaced02012-10-11 20:20:40 +00001636/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner08feb1e2007-04-24 04:04:35 +00001637/// the LSB for dense VBR encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001638uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001639 if ((V & 1) == 0)
1640 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001641 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001642 return -(V >> 1);
1643 // There is no such thing as -0 with integers. "-0" really means MININT.
1644 return 1ULL << 63;
1645}
1646
Chris Lattner44c17072007-04-26 02:46:40 +00001647/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1648/// values and aliases that we can.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001649std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00001650 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1651 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001652 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001653 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001654
Chris Lattner44c17072007-04-26 02:46:40 +00001655 GlobalInitWorklist.swap(GlobalInits);
1656 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001657 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001658 FunctionPrologueWorklist.swap(FunctionPrologues);
Chris Lattner44c17072007-04-26 02:46:40 +00001659
1660 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00001661 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001662 if (ValID >= ValueList.size()) {
1663 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00001664 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001665 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001666 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00001667 GlobalInitWorklist.back().first->setInitializer(C);
1668 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001669 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00001670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001671 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001672 }
1673
1674 while (!AliasInitWorklist.empty()) {
1675 unsigned ValID = AliasInitWorklist.back().second;
1676 if (ValID >= ValueList.size()) {
1677 AliasInits.push_back(AliasInitWorklist.back());
1678 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001679 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Rafael Espindola64c1e182014-06-03 02:41:57 +00001680 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00001681 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001682 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00001683 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001684 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001685 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001686
1687 while (!FunctionPrefixWorklist.empty()) {
1688 unsigned ValID = FunctionPrefixWorklist.back().second;
1689 if (ValID >= ValueList.size()) {
1690 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1691 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001692 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001693 FunctionPrefixWorklist.back().first->setPrefixData(C);
1694 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001695 return Error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001696 }
1697 FunctionPrefixWorklist.pop_back();
1698 }
1699
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001700 while (!FunctionPrologueWorklist.empty()) {
1701 unsigned ValID = FunctionPrologueWorklist.back().second;
1702 if (ValID >= ValueList.size()) {
1703 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1704 } else {
1705 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1706 FunctionPrologueWorklist.back().first->setPrologueData(C);
1707 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001708 return Error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001709 }
1710 FunctionPrologueWorklist.pop_back();
1711 }
1712
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001713 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00001714}
1715
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001716static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1717 SmallVector<uint64_t, 8> Words(Vals.size());
1718 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00001719 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001720
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001721 return APInt(TypeBits, Words);
1722}
1723
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001724std::error_code BitcodeReader::ParseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001725 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001726 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001727
1728 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001729
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001730 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00001731 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00001732 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001733 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001734 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001735
Chris Lattner27d38752013-01-20 02:13:19 +00001736 switch (Entry.Kind) {
1737 case BitstreamEntry::SubBlock: // Handled for us already.
1738 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001739 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001740 case BitstreamEntry::EndBlock:
1741 if (NextCstNo != ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001742 return Error("Invalid ronstant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00001743
Chris Lattner27d38752013-01-20 02:13:19 +00001744 // Once all the constants have been read, go through and resolve forward
1745 // references.
1746 ValueList.ResolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001747 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001748 case BitstreamEntry::Record:
1749 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00001750 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001751 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001752
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001753 // Read a record.
1754 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001755 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001756 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00001757 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001758 default: // Default behavior: unknown constant
1759 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00001760 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001761 break;
1762 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1763 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001764 return Error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00001765 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001766 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001767 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00001768 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001769 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00001770 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001771 break;
1772 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001773 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001774 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00001775 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00001776 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001777 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001778 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001779 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001780
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001781 APInt VInt = ReadWideAPInt(Record,
1782 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001783 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001784
Chris Lattner08feb1e2007-04-24 04:04:35 +00001785 break;
1786 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00001787 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00001788 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001789 return Error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00001790 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00001791 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1792 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00001793 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00001794 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1795 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001796 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00001797 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1798 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001799 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00001800 // Bits are not stored the same way as a normal i80 APInt, compensate.
1801 uint64_t Rearrange[2];
1802 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1803 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00001804 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1805 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001806 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001807 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1808 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001809 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001810 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1811 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001812 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001813 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001814 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00001815 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001816
Chris Lattnere14cb882007-05-04 19:11:41 +00001817 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1818 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001819 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001820
Chris Lattnere14cb882007-05-04 19:11:41 +00001821 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001822 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001823
Chris Lattner229907c2011-07-18 04:54:35 +00001824 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00001825 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001826 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00001827 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00001828 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001829 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1830 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001831 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001832 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00001833 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001834 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1835 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001836 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001837 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00001838 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00001839 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001840 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00001841 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001842 break;
1843 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001844 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00001845 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1846 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001847 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001848
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001849 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001850 V = ConstantDataArray::getString(Context, Elts,
1851 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00001852 break;
1853 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00001854 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1855 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001856 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001857
Chris Lattner372dd1e2012-01-30 00:51:16 +00001858 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1859 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001860
Chris Lattner372dd1e2012-01-30 00:51:16 +00001861 if (EltTy->isIntegerTy(8)) {
1862 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1863 if (isa<VectorType>(CurTy))
1864 V = ConstantDataVector::get(Context, Elts);
1865 else
1866 V = ConstantDataArray::get(Context, Elts);
1867 } else if (EltTy->isIntegerTy(16)) {
1868 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1869 if (isa<VectorType>(CurTy))
1870 V = ConstantDataVector::get(Context, Elts);
1871 else
1872 V = ConstantDataArray::get(Context, Elts);
1873 } else if (EltTy->isIntegerTy(32)) {
1874 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1875 if (isa<VectorType>(CurTy))
1876 V = ConstantDataVector::get(Context, Elts);
1877 else
1878 V = ConstantDataArray::get(Context, Elts);
1879 } else if (EltTy->isIntegerTy(64)) {
1880 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1881 if (isa<VectorType>(CurTy))
1882 V = ConstantDataVector::get(Context, Elts);
1883 else
1884 V = ConstantDataArray::get(Context, Elts);
1885 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001886 SmallVector<float, 16> Elts(Size);
1887 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001888 if (isa<VectorType>(CurTy))
1889 V = ConstantDataVector::get(Context, Elts);
1890 else
1891 V = ConstantDataArray::get(Context, Elts);
1892 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001893 SmallVector<double, 16> Elts(Size);
1894 std::transform(Record.begin(), Record.end(), Elts.begin(),
1895 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001896 if (isa<VectorType>(CurTy))
1897 V = ConstantDataVector::get(Context, Elts);
1898 else
1899 V = ConstantDataArray::get(Context, Elts);
1900 } else {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001901 return Error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00001902 }
1903 break;
1904 }
1905
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001906 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001907 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001908 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001909 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001910 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001911 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00001912 } else {
1913 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1914 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00001915 unsigned Flags = 0;
1916 if (Record.size() >= 4) {
1917 if (Opc == Instruction::Add ||
1918 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001919 Opc == Instruction::Mul ||
1920 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00001921 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1922 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1923 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1924 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00001925 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001926 Opc == Instruction::UDiv ||
1927 Opc == Instruction::LShr ||
1928 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00001929 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00001930 Flags |= SDivOperator::IsExact;
1931 }
1932 }
1933 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00001934 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001935 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001936 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001937 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001938 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001939 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001940 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00001941 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001942 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00001943 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00001944 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001945 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001946 return Error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00001947 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001948 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1949 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001950 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001951 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001952 }
Dan Gohman1639c392009-07-27 21:53:46 +00001953 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001954 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001955 if (Record.size() & 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001956 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001957 SmallVector<Constant*, 16> Elts;
Chris Lattnere14cb882007-05-04 19:11:41 +00001958 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001959 Type *ElTy = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001960 if (!ElTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001961 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001962 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1963 }
Jay Foaded8db7d2011-07-21 14:31:17 +00001964 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad2f5fc8c2011-07-21 15:15:37 +00001965 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1966 BitCode ==
1967 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00001968 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001969 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00001970 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001971 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001972 return Error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00001973
1974 Type *SelectorTy = Type::getInt1Ty(Context);
1975
1976 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1977 // vector. Otherwise, it must be a single bit.
1978 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1979 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1980 VTy->getNumElements());
1981
1982 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1983 SelectorTy),
1984 ValueList.getConstantFwdRef(Record[1],CurTy),
1985 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001986 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00001987 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001988 case bitc::CST_CODE_CE_EXTRACTELT
1989 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001990 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001991 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00001992 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001993 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001994 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001995 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001996 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001997 Constant *Op1 = nullptr;
1998 if (Record.size() == 4) {
1999 Type *IdxTy = getTypeByID(Record[2]);
2000 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002001 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002002 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2003 } else // TODO: Remove with llvm 4.0
2004 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2005 if (!Op1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002006 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002007 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002008 break;
2009 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002010 case bitc::CST_CODE_CE_INSERTELT
2011 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002012 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002013 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002014 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002015 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2016 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2017 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002018 Constant *Op2 = nullptr;
2019 if (Record.size() == 4) {
2020 Type *IdxTy = getTypeByID(Record[2]);
2021 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002022 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002023 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2024 } else // TODO: Remove with llvm 4.0
2025 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2026 if (!Op2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002027 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002028 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002029 break;
2030 }
2031 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002032 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002033 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002034 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002035 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2036 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002037 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002038 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002039 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002040 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002041 break;
2042 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002043 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002044 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2045 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002046 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002047 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002048 return Error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002049 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2050 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002051 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002052 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002053 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002054 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002055 break;
2056 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002057 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002058 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002059 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002060 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002061 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002062 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002063 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2064 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2065
Duncan Sands9dff9be2010-02-15 16:12:20 +00002066 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002067 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002068 else
Owen Anderson487375e2009-07-29 18:55:55 +00002069 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002070 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002071 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002072 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002073 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002074 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002075 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002076 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002077 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002078 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002079 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002080 unsigned AsmStrSize = Record[1];
2081 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002082 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002083 unsigned ConstStrSize = Record[2+AsmStrSize];
2084 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002085 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002086
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002087 for (unsigned i = 0; i != AsmStrSize; ++i)
2088 AsmStr += (char)Record[2+i];
2089 for (unsigned i = 0; i != ConstStrSize; ++i)
2090 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002091 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002092 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002093 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002094 break;
2095 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002096 // This version adds support for the asm dialect keywords (e.g.,
2097 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002098 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002099 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002100 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002101 std::string AsmStr, ConstrStr;
2102 bool HasSideEffects = Record[0] & 1;
2103 bool IsAlignStack = (Record[0] >> 1) & 1;
2104 unsigned AsmDialect = Record[0] >> 2;
2105 unsigned AsmStrSize = Record[1];
2106 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002107 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002108 unsigned ConstStrSize = Record[2+AsmStrSize];
2109 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002110 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002111
2112 for (unsigned i = 0; i != AsmStrSize; ++i)
2113 AsmStr += (char)Record[2+i];
2114 for (unsigned i = 0; i != ConstStrSize; ++i)
2115 ConstrStr += (char)Record[3+AsmStrSize+i];
2116 PointerType *PTy = cast<PointerType>(CurTy);
2117 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2118 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002119 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002120 break;
2121 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002122 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002123 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002124 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002125 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002126 if (!FnTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002127 return Error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002128 Function *Fn =
2129 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002130 if (!Fn)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002131 return Error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002132
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00002133 // Don't let Fn get dematerialized.
2134 BlockAddressesTaken.insert(Fn);
2135
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002136 // If the function is already parsed we can insert the block address right
2137 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002138 BasicBlock *BB;
2139 unsigned BBID = Record[2];
2140 if (!BBID)
2141 // Invalid reference to entry block.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002142 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002143 if (!Fn->empty()) {
2144 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002145 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002146 if (BBI == BBE)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002147 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002148 ++BBI;
2149 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002150 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002151 } else {
2152 // Otherwise insert a placeholder and remember it so it can be inserted
2153 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002154 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2155 if (FwdBBs.empty())
2156 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002157 if (FwdBBs.size() < BBID + 1)
2158 FwdBBs.resize(BBID + 1);
2159 if (!FwdBBs[BBID])
2160 FwdBBs[BBID] = BasicBlock::Create(Context);
2161 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002162 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002163 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002164 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002165 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002166 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002167
Chris Lattner83930552007-05-01 07:01:57 +00002168 ValueList.AssignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002169 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002170 }
2171}
Chris Lattner1314b992007-04-22 06:23:29 +00002172
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002173std::error_code BitcodeReader::ParseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002174 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002175 return Error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002176
Chad Rosierca2567b2011-12-07 21:44:12 +00002177 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002178 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00002179 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002180 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002181
Chris Lattner27d38752013-01-20 02:13:19 +00002182 switch (Entry.Kind) {
2183 case BitstreamEntry::SubBlock: // Handled for us already.
2184 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002185 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002186 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002187 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002188 case BitstreamEntry::Record:
2189 // The interesting case.
2190 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002191 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002192
Chad Rosierca2567b2011-12-07 21:44:12 +00002193 // Read a use list record.
2194 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002195 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002196 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002197 default: // Default behavior: unknown type.
2198 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002199 case bitc::USELIST_CODE_BB:
2200 IsBB = true;
2201 // fallthrough
2202 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002203 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002204 if (RecordLength < 3)
2205 // Records should have at least an ID and two indexes.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002206 return Error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002207 unsigned ID = Record.back();
2208 Record.pop_back();
2209
2210 Value *V;
2211 if (IsBB) {
2212 assert(ID < FunctionBBs.size() && "Basic block not found");
2213 V = FunctionBBs[ID];
2214 } else
2215 V = ValueList[ID];
2216 unsigned NumUses = 0;
2217 SmallDenseMap<const Use *, unsigned, 16> Order;
2218 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002219 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002220 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002221 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002222 }
2223 if (Order.size() != Record.size() || NumUses > Record.size())
2224 // Mismatches can happen if the functions are being materialized lazily
2225 // (out-of-order), or a value has been upgraded.
2226 break;
2227
2228 V->sortUseList([&](const Use &L, const Use &R) {
2229 return Order.lookup(&L) < Order.lookup(&R);
2230 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002231 break;
2232 }
2233 }
2234 }
2235}
2236
Chris Lattner85b7b402007-05-01 05:52:21 +00002237/// RememberAndSkipFunctionBody - When we see the block for a function body,
2238/// remember where it is and then skip it. This lets us lazily deserialize the
2239/// functions.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002240std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002241 // Get the function we are talking about.
2242 if (FunctionsWithBodies.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002243 return Error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002245 Function *Fn = FunctionsWithBodies.back();
2246 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002247
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002248 // Save the current stream state.
2249 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002250 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002251
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002252 // Skip over the function block for now.
2253 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002254 return Error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002255 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002256}
2257
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002258std::error_code BitcodeReader::GlobalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002259 // Patch the initializers for globals and aliases up.
2260 ResolveGlobalAndAliasInits();
2261 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002262 return Error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002263
2264 // Look for intrinsic functions which need to be upgraded at some point
2265 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2266 FI != FE; ++FI) {
2267 Function *NewFn;
2268 if (UpgradeIntrinsicFunction(FI, NewFn))
2269 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2270 }
2271
2272 // Look for global variables which need to be renamed.
2273 for (Module::global_iterator
2274 GI = TheModule->global_begin(), GE = TheModule->global_end();
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002275 GI != GE;) {
2276 GlobalVariable *GV = GI++;
2277 UpgradeGlobalVariable(GV);
2278 }
2279
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002280 // Force deallocation of memory for these vectors to favor the client that
2281 // want lazy deserialization.
2282 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2283 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002284 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002285}
2286
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002287std::error_code BitcodeReader::ParseModule(bool Resume) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002288 if (Resume)
2289 Stream.JumpToBit(NextUnreadBit);
2290 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002291 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002292
Chris Lattner1314b992007-04-22 06:23:29 +00002293 SmallVector<uint64_t, 64> Record;
2294 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00002295 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00002296
2297 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002298 while (1) {
2299 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002300
Chris Lattner27d38752013-01-20 02:13:19 +00002301 switch (Entry.Kind) {
2302 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002303 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002304 case BitstreamEntry::EndBlock:
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002305 return GlobalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00002306
Chris Lattner27d38752013-01-20 02:13:19 +00002307 case BitstreamEntry::SubBlock:
2308 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00002309 default: // Skip unknown content.
2310 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002311 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002312 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002313 case bitc::BLOCKINFO_BLOCK_ID:
2314 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002315 return Error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002316 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002317 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002318 if (std::error_code EC = ParseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002319 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002320 break;
Bill Wendlingba629332013-02-10 23:24:25 +00002321 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002322 if (std::error_code EC = ParseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002323 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00002324 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002325 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002326 if (std::error_code EC = ParseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002327 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002328 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002329 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002330 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002331 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002332 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002333 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002334 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002335 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002336 return EC;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002337 if (std::error_code EC = ResolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002338 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002339 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002340 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002341 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002342 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00002343 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002344 case bitc::FUNCTION_BLOCK_ID:
2345 // If this is the first function body we've seen, reverse the
2346 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002347 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002348 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002349 if (std::error_code EC = GlobalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002350 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002351 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002352 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002353
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002354 if (std::error_code EC = RememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002355 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002356 // For streaming bitcode, suspend parsing when we reach the function
2357 // bodies. Subsequent materialization calls will resume it when
2358 // necessary. For streaming, the function bodies must be at the end of
2359 // the bitcode. If the bitcode file is old, the symbol table will be
2360 // at the end instead and will not have been seen yet. In this case,
2361 // just finish the parse now.
2362 if (LazyStreamer && SeenValueSymbolTable) {
2363 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002364 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002365 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002366 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002367 case bitc::USELIST_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002368 if (std::error_code EC = ParseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002369 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00002370 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002371 }
2372 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002373
Chris Lattner27d38752013-01-20 02:13:19 +00002374 case BitstreamEntry::Record:
2375 // The interesting case.
2376 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002377 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002378
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002379
Chris Lattner1314b992007-04-22 06:23:29 +00002380 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002381 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00002382 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002383 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00002384 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002385 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002386 // Only version #0 and #1 are supported so far.
2387 unsigned module_version = Record[0];
2388 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002389 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002390 return Error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002391 case 0:
2392 UseRelativeIDs = false;
2393 break;
2394 case 1:
2395 UseRelativeIDs = true;
2396 break;
2397 }
Chris Lattner1314b992007-04-22 06:23:29 +00002398 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002399 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002400 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002401 std::string S;
2402 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002403 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002404 TheModule->setTargetTriple(S);
2405 break;
2406 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002407 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002408 std::string S;
2409 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002410 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002411 TheModule->setDataLayout(S);
2412 break;
2413 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002414 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002415 std::string S;
2416 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002417 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002418 TheModule->setModuleInlineAsm(S);
2419 break;
2420 }
Bill Wendling706d3d62012-11-28 08:41:48 +00002421 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2422 // FIXME: Remove in 4.0.
2423 std::string S;
2424 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002425 return Error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00002426 // Ignore value.
2427 break;
2428 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002429 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002430 std::string S;
2431 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002432 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002433 SectionTable.push_back(S);
2434 break;
2435 }
Gordon Henriksend930f912008-08-17 18:44:35 +00002436 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00002437 std::string S;
2438 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002439 return Error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00002440 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00002441 break;
2442 }
David Majnemerdad0a642014-06-27 18:19:56 +00002443 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2444 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002445 return Error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00002446 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2447 unsigned ComdatNameSize = Record[1];
2448 std::string ComdatName;
2449 ComdatName.reserve(ComdatNameSize);
2450 for (unsigned i = 0; i != ComdatNameSize; ++i)
2451 ComdatName += (char)Record[2 + i];
2452 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2453 C->setSelectionKind(SK);
2454 ComdatList.push_back(C);
2455 break;
2456 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002457 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00002458 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00002459 // unnamed_addr, externally_initialized, dllstorageclass,
2460 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00002461 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00002462 if (Record.size() < 6)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002463 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002464 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002465 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002466 return Error("Invalid record");
Duncan Sands19d0b472010-02-16 11:11:14 +00002467 if (!Ty->isPointerTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002468 return Error("Invalid type for value");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002469 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattner1314b992007-04-22 06:23:29 +00002470 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002471
Chris Lattner1314b992007-04-22 06:23:29 +00002472 bool isConstant = Record[1];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002473 uint64_t RawLinkage = Record[3];
2474 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00002475 unsigned Alignment;
2476 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2477 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002478 std::string Section;
2479 if (Record[5]) {
2480 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002481 return Error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00002482 Section = SectionTable[Record[5]-1];
2483 }
Chris Lattner4b00d922007-04-23 16:04:05 +00002484 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002485 // Local linkage must have default visibility.
2486 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2487 // FIXME: Change to an error if non-default in 4.0.
Chris Lattner53862f72007-05-06 19:27:46 +00002488 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002489
2490 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00002491 if (Record.size() > 7)
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002492 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00002493
Rafael Espindola45e6c192011-01-08 16:42:36 +00002494 bool UnnamedAddr = false;
2495 if (Record.size() > 8)
2496 UnnamedAddr = Record[8];
2497
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002498 bool ExternallyInitialized = false;
2499 if (Record.size() > 9)
2500 ExternallyInitialized = Record[9];
2501
Chris Lattner1314b992007-04-22 06:23:29 +00002502 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00002503 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002504 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00002505 NewGV->setAlignment(Alignment);
2506 if (!Section.empty())
2507 NewGV->setSection(Section);
2508 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00002509 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002510
Nico Rieck7157bb72014-01-14 15:22:47 +00002511 if (Record.size() > 10)
2512 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2513 else
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002514 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00002515
Chris Lattnerccaa4482007-04-23 21:26:05 +00002516 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002517
Chris Lattner47d131b2007-04-24 00:18:21 +00002518 // Remember which value to use for the global initializer.
2519 if (unsigned InitID = Record[2])
2520 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00002521
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002522 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00002523 if (unsigned ComdatID = Record[11]) {
2524 assert(ComdatID <= ComdatList.size());
2525 NewGV->setComdat(ComdatList[ComdatID - 1]);
2526 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002527 } else if (hasImplicitComdat(RawLinkage)) {
2528 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2529 }
Chris Lattner1314b992007-04-22 06:23:29 +00002530 break;
2531 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002532 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00002533 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002534 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00002535 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002536 if (Record.size() < 8)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002537 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002538 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002539 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002540 return Error("Invalid record");
Duncan Sands19d0b472010-02-16 11:11:14 +00002541 if (!Ty->isPointerTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002542 return Error("Invalid type for value");
Chris Lattner229907c2011-07-18 04:54:35 +00002543 FunctionType *FTy =
Chris Lattner1314b992007-04-22 06:23:29 +00002544 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2545 if (!FTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002546 return Error("Invalid type for value");
Chris Lattner1314b992007-04-22 06:23:29 +00002547
Gabor Greife9ecc682008-04-06 20:25:17 +00002548 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2549 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00002550
Sandeep Patel68c5f472009-09-02 08:44:58 +00002551 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002552 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002553 uint64_t RawLinkage = Record[3];
2554 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00002555 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002556
JF Bastien30bf96b2015-02-22 19:32:03 +00002557 unsigned Alignment;
2558 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2559 return EC;
2560 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002561 if (Record[6]) {
2562 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002563 return Error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002564 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00002565 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002566 // Local linkage must have default visibility.
2567 if (!Func->hasLocalLinkage())
2568 // FIXME: Change to an error if non-default in 4.0.
2569 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00002570 if (Record.size() > 8 && Record[8]) {
Gordon Henriksend930f912008-08-17 18:44:35 +00002571 if (Record[8]-1 > GCTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002572 return Error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00002573 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00002574 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00002575 bool UnnamedAddr = false;
2576 if (Record.size() > 9)
2577 UnnamedAddr = Record[9];
2578 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002579 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002580 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00002581
2582 if (Record.size() > 11)
2583 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2584 else
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002585 UpgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00002586
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002587 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00002588 if (unsigned ComdatID = Record[12]) {
2589 assert(ComdatID <= ComdatList.size());
2590 Func->setComdat(ComdatList[ComdatID - 1]);
2591 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002592 } else if (hasImplicitComdat(RawLinkage)) {
2593 Func->setComdat(reinterpret_cast<Comdat *>(1));
2594 }
David Majnemerdad0a642014-06-27 18:19:56 +00002595
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002596 if (Record.size() > 13 && Record[13] != 0)
2597 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2598
Chris Lattnerccaa4482007-04-23 21:26:05 +00002599 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002600
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002601 // If this is a function with a body, remember the prototype we are
2602 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002603 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00002604 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002605 FunctionsWithBodies.push_back(Func);
Rafael Espindola1b47a282014-10-23 15:20:05 +00002606 if (LazyStreamer)
2607 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002608 }
Chris Lattner1314b992007-04-22 06:23:29 +00002609 break;
2610 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002611 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00002612 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00002613 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00002614 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002615 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002616 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002617 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002618 return Error("Invalid record");
Rafael Espindolaa8004452014-05-16 14:22:33 +00002619 auto *PTy = dyn_cast<PointerType>(Ty);
2620 if (!PTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002621 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002622
Rafael Espindolaa8004452014-05-16 14:22:33 +00002623 auto *NewGA =
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00002624 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00002625 getDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002626 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002627 // Local linkage must have default visibility.
2628 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2629 // FIXME: Change to an error if non-default in 4.0.
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002630 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00002631 if (Record.size() > 4)
2632 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2633 else
2634 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00002635 if (Record.size() > 5)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00002636 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00002637 if (Record.size() > 6)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00002638 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00002639 ValueList.push_back(NewGA);
2640 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2641 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002642 }
Chris Lattner831d4202007-04-26 03:27:58 +00002643 /// MODULE_CODE_PURGEVALS: [numvals]
2644 case bitc::MODULE_CODE_PURGEVALS:
2645 // Trim down the value list to the specified size.
2646 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002647 return Error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00002648 ValueList.shrinkTo(Record[0]);
2649 break;
2650 }
Chris Lattner1314b992007-04-22 06:23:29 +00002651 Record.clear();
2652 }
Chris Lattner1314b992007-04-22 06:23:29 +00002653}
2654
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002655std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002656 TheModule = nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002657
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002658 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002659 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002660
Chris Lattner1314b992007-04-22 06:23:29 +00002661 // Sniff for the signature.
2662 if (Stream.Read(8) != 'B' ||
2663 Stream.Read(8) != 'C' ||
2664 Stream.Read(4) != 0x0 ||
2665 Stream.Read(4) != 0xC ||
2666 Stream.Read(4) != 0xE ||
2667 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002668 return Error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669
Chris Lattner1314b992007-04-22 06:23:29 +00002670 // We expect a number of well-defined blocks, though we don't necessarily
2671 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002672 while (1) {
2673 if (Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002674 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002675
Chris Lattner27d38752013-01-20 02:13:19 +00002676 BitstreamEntry Entry =
2677 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00002678
Chris Lattner27d38752013-01-20 02:13:19 +00002679 switch (Entry.Kind) {
2680 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002681 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002682 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002683 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002684
Chris Lattner27d38752013-01-20 02:13:19 +00002685 case BitstreamEntry::SubBlock:
2686 switch (Entry.ID) {
2687 case bitc::BLOCKINFO_BLOCK_ID:
2688 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002689 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002690 break;
2691 case bitc::MODULE_BLOCK_ID:
2692 // Reject multiple MODULE_BLOCK's in a single bitstream.
2693 if (TheModule)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002694 return Error("Invalid multiple blocks");
Chris Lattner27d38752013-01-20 02:13:19 +00002695 TheModule = M;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002696 if (std::error_code EC = ParseModule(false))
Rafael Espindola48da4f42013-11-04 16:16:24 +00002697 return EC;
2698 if (LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002699 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002700 break;
2701 default:
2702 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002703 return Error("Invalid record");
Chris Lattner27d38752013-01-20 02:13:19 +00002704 break;
2705 }
2706 continue;
2707 case BitstreamEntry::Record:
2708 // There should be no records in the top-level of blocks.
Joe Abbey97b7a172013-02-06 22:14:06 +00002709
Chris Lattner27d38752013-01-20 02:13:19 +00002710 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosiera15e3aa2011-08-09 22:23:40 +00002711 // to the end of them. If this file size is a multiple of 4 but not 8, we
2712 // have to read and ignore these final 4 bytes :-(
Chris Lattner27d38752013-01-20 02:13:19 +00002713 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002714 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling318f03f2012-07-19 00:15:11 +00002715 Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002716 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002717
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002718 return Error("Invalid record");
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002719 }
Chris Lattner1314b992007-04-22 06:23:29 +00002720 }
Chris Lattner1314b992007-04-22 06:23:29 +00002721}
Chris Lattner6694f602007-04-29 07:54:31 +00002722
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002723ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00002724 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002725 return Error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00002726
2727 SmallVector<uint64_t, 64> Record;
2728
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002729 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00002730 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002731 while (1) {
2732 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002733
Chris Lattner27d38752013-01-20 02:13:19 +00002734 switch (Entry.Kind) {
2735 case BitstreamEntry::SubBlock: // Handled for us already.
2736 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002737 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002738 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00002739 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00002740 case BitstreamEntry::Record:
2741 // The interesting case.
2742 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00002743 }
2744
2745 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002746 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00002747 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00002748 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002749 std::string S;
2750 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002751 return Error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002752 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00002753 break;
2754 }
2755 }
2756 Record.clear();
2757 }
Rafael Espindolae6107792014-07-04 20:05:56 +00002758 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00002759}
2760
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002761ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002762 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002763 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00002764
2765 // Sniff for the signature.
2766 if (Stream.Read(8) != 'B' ||
2767 Stream.Read(8) != 'C' ||
2768 Stream.Read(4) != 0x0 ||
2769 Stream.Read(4) != 0xC ||
2770 Stream.Read(4) != 0xE ||
2771 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002772 return Error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00002773
2774 // We expect a number of well-defined blocks, though we don't necessarily
2775 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002776 while (1) {
2777 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002778
Chris Lattner27d38752013-01-20 02:13:19 +00002779 switch (Entry.Kind) {
2780 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002781 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002782 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002783 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002784
Chris Lattner27d38752013-01-20 02:13:19 +00002785 case BitstreamEntry::SubBlock:
2786 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00002787 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00002788
Chris Lattner27d38752013-01-20 02:13:19 +00002789 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00002790 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002791 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002792 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002793
Chris Lattner27d38752013-01-20 02:13:19 +00002794 case BitstreamEntry::Record:
2795 Stream.skipRecord(Entry.ID);
2796 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00002797 }
2798 }
Bill Wendling0198ce02010-10-06 01:22:42 +00002799}
2800
Devang Patelaf206b82009-09-18 19:26:43 +00002801/// ParseMetadataAttachment - Parse metadata attachments.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002802std::error_code BitcodeReader::ParseMetadataAttachment() {
Devang Patelaf206b82009-09-18 19:26:43 +00002803 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002804 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002805
Devang Patelaf206b82009-09-18 19:26:43 +00002806 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00002807 while (1) {
2808 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002809
Chris Lattner27d38752013-01-20 02:13:19 +00002810 switch (Entry.Kind) {
2811 case BitstreamEntry::SubBlock: // Handled for us already.
2812 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002813 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002814 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002815 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002816 case BitstreamEntry::Record:
2817 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00002818 break;
2819 }
Chris Lattner27d38752013-01-20 02:13:19 +00002820
Devang Patelaf206b82009-09-18 19:26:43 +00002821 // Read a metadata attachment record.
2822 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00002823 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00002824 default: // Default behavior: ignore.
2825 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00002826 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00002827 unsigned RecordLength = Record.size();
2828 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002829 return Error("Invalid record");
Devang Patelaf206b82009-09-18 19:26:43 +00002830 Instruction *Inst = InstructionList[Record[0]];
2831 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00002832 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00002833 DenseMap<unsigned, unsigned>::iterator I =
2834 MDKindMap.find(Kind);
2835 if (I == MDKindMap.end())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002836 return Error("Invalid ID");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002837 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2838 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00002839 // Drop the attachment. This used to be legal, but there's no
2840 // upgrade path.
2841 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002842 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00002843 if (I->second == LLVMContext::MD_tbaa)
2844 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00002845 }
2846 break;
2847 }
2848 }
2849 }
Devang Patelaf206b82009-09-18 19:26:43 +00002850}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002851
Chris Lattner85b7b402007-05-01 05:52:21 +00002852/// ParseFunctionBody - Lazily parse the specified function body block.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002853std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002854 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002855 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002856
Nick Lewyckya72e1af2010-02-25 08:30:17 +00002857 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00002858 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00002859 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002860
Chris Lattner85b7b402007-05-01 05:52:21 +00002861 // Add all the function arguments to the value table.
2862 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2863 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002864
Chris Lattner83930552007-05-01 07:01:57 +00002865 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00002866 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00002867 unsigned CurBBNo = 0;
2868
Chris Lattner07d09ed2010-04-03 02:17:50 +00002869 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002870 auto getLastInstruction = [&]() -> Instruction * {
2871 if (CurBB && !CurBB->empty())
2872 return &CurBB->back();
2873 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2874 !FunctionBBs[CurBBNo - 1]->empty())
2875 return &FunctionBBs[CurBBNo - 1]->back();
2876 return nullptr;
2877 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002878
Chris Lattner85b7b402007-05-01 05:52:21 +00002879 // Read all the records.
2880 SmallVector<uint64_t, 64> Record;
2881 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002882 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002883
Chris Lattner27d38752013-01-20 02:13:19 +00002884 switch (Entry.Kind) {
2885 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002886 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002887 case BitstreamEntry::EndBlock:
2888 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00002889
Chris Lattner27d38752013-01-20 02:13:19 +00002890 case BitstreamEntry::SubBlock:
2891 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00002892 default: // Skip unknown content.
2893 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002894 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00002895 break;
2896 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002897 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002898 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00002899 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00002900 break;
2901 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002902 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002903 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00002904 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002905 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002906 if (std::error_code EC = ParseMetadataAttachment())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002907 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002908 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002909 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002910 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002911 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002912 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002913 case bitc::USELIST_BLOCK_ID:
2914 if (std::error_code EC = ParseUseLists())
2915 return EC;
2916 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002917 }
2918 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002919
Chris Lattner27d38752013-01-20 02:13:19 +00002920 case BitstreamEntry::Record:
2921 // The interesting case.
2922 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002923 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002924
Chris Lattner85b7b402007-05-01 05:52:21 +00002925 // Read a record.
2926 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002927 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002928 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002929 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00002930 default: // Default behavior: reject
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002931 return Error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002932 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00002933 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002934 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00002935 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00002936 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002937
2938 // See if anything took the address of blocks in this function.
2939 auto BBFRI = BasicBlockFwdRefs.find(F);
2940 if (BBFRI == BasicBlockFwdRefs.end()) {
2941 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2942 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2943 } else {
2944 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002945 // Check for invalid basic block references.
2946 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002947 return Error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002948 assert(!BBRefs.empty() && "Unexpected empty array");
2949 assert(!BBRefs.front() && "Invalid reference to entry block");
2950 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2951 ++I)
2952 if (I < RE && BBRefs[I]) {
2953 BBRefs[I]->insertInto(F);
2954 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002955 } else {
2956 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2957 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002958
2959 // Erase from the table.
2960 BasicBlockFwdRefs.erase(BBFRI);
2961 }
2962
Chris Lattner83930552007-05-01 07:01:57 +00002963 CurBB = FunctionBBs[0];
2964 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002965 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002966
Chris Lattner07d09ed2010-04-03 02:17:50 +00002967 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2968 // This record indicates that the last instruction is at the same
2969 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002970 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002971
Craig Topper2617dcc2014-04-15 06:32:26 +00002972 if (!I)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002973 return Error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00002974 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002975 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002976 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002977
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00002978 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002979 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00002980 if (!I || Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002981 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002982
Chris Lattner07d09ed2010-04-03 02:17:50 +00002983 unsigned Line = Record[0], Col = Record[1];
2984 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002985
Craig Topper2617dcc2014-04-15 06:32:26 +00002986 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002987 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2988 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2989 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2990 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002991 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002992 continue;
2993 }
2994
Chris Lattnere9759c22007-05-06 00:21:25 +00002995 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2996 unsigned OpNum = 0;
2997 Value *LHS, *RHS;
2998 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002999 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003000 OpNum+1 > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003001 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003002
Dan Gohman0ebd6962009-07-20 21:19:07 +00003003 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003004 if (Opc == -1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003005 return Error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003006 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003007 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003008 if (OpNum < Record.size()) {
3009 if (Opc == Instruction::Add ||
3010 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003011 Opc == Instruction::Mul ||
3012 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003013 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003014 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003015 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003016 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003017 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003018 Opc == Instruction::UDiv ||
3019 Opc == Instruction::LShr ||
3020 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003021 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003022 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003023 } else if (isa<FPMathOperator>(I)) {
3024 FastMathFlags FMF;
Michael Ilseman65f14352012-12-09 21:12:04 +00003025 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3026 FMF.setUnsafeAlgebra();
3027 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3028 FMF.setNoNaNs();
3029 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3030 FMF.setNoInfs();
3031 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3032 FMF.setNoSignedZeros();
3033 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3034 FMF.setAllowReciprocal();
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003035 if (FMF.any())
3036 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003037 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003038
Dan Gohman1b849082009-09-07 23:54:19 +00003039 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003040 break;
3041 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003042 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3043 unsigned OpNum = 0;
3044 Value *Op;
3045 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3046 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003047 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003048
Chris Lattner229907c2011-07-18 04:54:35 +00003049 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnere9759c22007-05-06 00:21:25 +00003050 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003051 if (Opc == -1 || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003052 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003053 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003054 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3055 if (Temp) {
3056 InstructionList.push_back(Temp);
3057 CurBB->getInstList().push_back(Temp);
3058 }
3059 } else {
3060 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3061 }
Devang Patelaf206b82009-09-18 19:26:43 +00003062 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003063 break;
3064 }
Dan Gohman1639c392009-07-27 21:53:46 +00003065 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattnere14cb882007-05-04 19:11:41 +00003066 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003067 unsigned OpNum = 0;
3068 Value *BasePtr;
3069 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003070 return Error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003071
Chris Lattner5285b5e2007-05-02 05:46:45 +00003072 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003073 while (OpNum != Record.size()) {
3074 Value *Op;
3075 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003076 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003077 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003078 }
3079
Jay Foadd1b78492011-07-25 09:48:08 +00003080 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003081 InstructionList.push_back(I);
Dan Gohman1639c392009-07-27 21:53:46 +00003082 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohman1b849082009-09-07 23:54:19 +00003083 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003084 break;
3085 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003086
Dan Gohman1ecaf452008-05-31 00:58:22 +00003087 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3088 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003089 unsigned OpNum = 0;
3090 Value *Agg;
3091 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003092 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003093
Dan Gohman1ecaf452008-05-31 00:58:22 +00003094 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003095 Type *CurTy = Agg->getType();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003096 for (unsigned RecSize = Record.size();
3097 OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003098 bool IsArray = CurTy->isArrayTy();
3099 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003100 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003101
3102 if (!IsStruct && !IsArray)
3103 return Error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003104 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003105 return Error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003106 if (IsStruct && Index >= CurTy->subtypes().size())
3107 return Error("EXTRACTVAL: Invalid struct index");
3108 if (IsArray && Index >= CurTy->getArrayNumElements())
3109 return Error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003110 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003111
3112 if (IsStruct)
3113 CurTy = CurTy->subtypes()[Index];
3114 else
3115 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003116 }
3117
Jay Foad57aa6362011-07-13 10:26:04 +00003118 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003119 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003120 break;
3121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003122
Dan Gohman1ecaf452008-05-31 00:58:22 +00003123 case bitc::FUNC_CODE_INST_INSERTVAL: {
3124 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003125 unsigned OpNum = 0;
3126 Value *Agg;
3127 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003128 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003129 Value *Val;
3130 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003131 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003132
Dan Gohman1ecaf452008-05-31 00:58:22 +00003133 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003134 Type *CurTy = Agg->getType();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003135 for (unsigned RecSize = Record.size();
3136 OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003137 bool IsArray = CurTy->isArrayTy();
3138 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003139 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003140
3141 if (!IsStruct && !IsArray)
3142 return Error("INSERTVAL: Invalid type");
3143 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3144 return Error("Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003145 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003146 return Error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003147 if (IsStruct && Index >= CurTy->subtypes().size())
3148 return Error("INSERTVAL: Invalid struct index");
3149 if (IsArray && Index >= CurTy->getArrayNumElements())
3150 return Error("INSERTVAL: Invalid array index");
3151
Dan Gohman1ecaf452008-05-31 00:58:22 +00003152 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003153 if (IsStruct)
3154 CurTy = CurTy->subtypes()[Index];
3155 else
3156 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003157 }
3158
Jay Foad57aa6362011-07-13 10:26:04 +00003159 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003160 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003161 break;
3162 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003163
Chris Lattnere9759c22007-05-06 00:21:25 +00003164 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003165 // obsolete form of select
3166 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003167 unsigned OpNum = 0;
3168 Value *TrueVal, *FalseVal, *Cond;
3169 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003170 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3171 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003172 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003173
Dan Gohmanc5d28922008-09-16 01:01:33 +00003174 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003175 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003176 break;
3177 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003178
Dan Gohmanc5d28922008-09-16 01:01:33 +00003179 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3180 // new form of select
3181 // handles select i1 or select [N x i1]
3182 unsigned OpNum = 0;
3183 Value *TrueVal, *FalseVal, *Cond;
3184 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003185 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003186 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003187 return Error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003188
3189 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003190 if (VectorType* vector_type =
3191 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003192 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003193 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003194 return Error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003195 } else {
3196 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003197 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003198 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003199 }
3200
Gabor Greife9ecc682008-04-06 20:25:17 +00003201 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003202 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003203 break;
3204 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003205
Chris Lattner1fc27f02007-05-02 05:16:49 +00003206 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003207 unsigned OpNum = 0;
3208 Value *Vec, *Idx;
3209 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003210 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003211 return Error("Invalid record");
Eric Christopherc9742252009-07-25 02:28:41 +00003212 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003213 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003214 break;
3215 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003216
Chris Lattner1fc27f02007-05-02 05:16:49 +00003217 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003218 unsigned OpNum = 0;
3219 Value *Vec, *Elt, *Idx;
3220 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003221 popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003222 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003223 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003224 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003225 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003226 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003227 break;
3228 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003229
Chris Lattnere9759c22007-05-06 00:21:25 +00003230 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3231 unsigned OpNum = 0;
3232 Value *Vec1, *Vec2, *Mask;
3233 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003234 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003235 return Error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003236
Mon P Wang25f01062008-11-10 04:46:22 +00003237 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003238 return Error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003239 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003240 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003241 break;
3242 }
Mon P Wang25f01062008-11-10 04:46:22 +00003243
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003244 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3245 // Old form of ICmp/FCmp returning bool
3246 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3247 // both legal on vectors but had different behaviour.
3248 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3249 // FCmp/ICmp returning bool or vector of bool
3250
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003251 unsigned OpNum = 0;
3252 Value *LHS, *RHS;
3253 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003254 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003255 OpNum+1 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003256 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003257
Duncan Sands9dff9be2010-02-15 16:12:20 +00003258 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003259 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003260 else
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003261 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003262 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003263 break;
3264 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003265
Chris Lattnere53603e2007-05-02 04:27:25 +00003266 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003267 {
3268 unsigned Size = Record.size();
3269 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003270 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003271 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003272 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003273 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003274
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003275 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003276 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003277 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003278 return Error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003279 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003280 return Error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003281
Chris Lattnerf1c87102011-06-17 18:09:11 +00003282 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003283 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003284 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003285 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003286 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003287 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003288 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003289 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003290 if (!TrueDest)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003291 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003292
Devang Patelaf206b82009-09-18 19:26:43 +00003293 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003294 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003295 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003296 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003297 else {
3298 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003299 Value *Cond = getValue(Record, 2, NextValueNo,
3300 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003301 if (!FalseDest || !Cond)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003302 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003303 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003304 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003305 }
3306 break;
3307 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003308 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003309 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003310 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003311 // "New" SwitchInst format with case ranges. The changes to write this
3312 // format were reverted but we still recognize bitcode that uses it.
3313 // Hopefully someday we will have support for case ranges and can use
3314 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003315
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003316 Type *OpTy = getTypeByID(Record[1]);
3317 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3318
Jan Wen Voungafaced02012-10-11 20:20:40 +00003319 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003320 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003321 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003322 return Error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003323
3324 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003325
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003326 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3327 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003328
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003329 unsigned CurIdx = 5;
3330 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003331 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003332 unsigned NumItems = Record[CurIdx++];
3333 for (unsigned ci = 0; ci != NumItems; ++ci) {
3334 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003335
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003336 APInt Low;
3337 unsigned ActiveWords = 1;
3338 if (ValueBitWidth > 64)
3339 ActiveWords = Record[CurIdx++];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003340 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3341 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003342 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003343
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003344 if (!isSingleNumber) {
3345 ActiveWords = 1;
3346 if (ValueBitWidth > 64)
3347 ActiveWords = Record[CurIdx++];
3348 APInt High =
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003349 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3350 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003351 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003352
3353 // FIXME: It is not clear whether values in the range should be
3354 // compared as signed or unsigned values. The partially
3355 // implemented changes that used this format in the past used
3356 // unsigned comparisons.
3357 for ( ; Low.ule(High); ++Low)
3358 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003359 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003360 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003361 }
3362 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00003363 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3364 cve = CaseVals.end(); cvi != cve; ++cvi)
3365 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003366 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003367 I = SI;
3368 break;
3369 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003370
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003371 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003372
Chris Lattner5285b5e2007-05-02 05:46:45 +00003373 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003374 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003375 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003376 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003377 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003378 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003379 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003380 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00003381 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00003382 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003383 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003384 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00003385 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3386 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003387 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00003388 delete SI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003389 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003390 }
3391 SI->addCase(CaseVal, DestBB);
3392 }
3393 I = SI;
3394 break;
3395 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003396 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00003397 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003398 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003399 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003400 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003401 if (!OpTy || !Address)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003402 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003403 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003404 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00003405 InstructionList.push_back(IBI);
3406 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3407 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3408 IBI->addDestination(DestBB);
3409 } else {
3410 delete IBI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003411 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003412 }
3413 }
3414 I = IBI;
3415 break;
3416 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003417
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003418 case bitc::FUNC_CODE_INST_INVOKE: {
3419 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003420 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003421 return Error("Invalid record");
Bill Wendlinge94d8432012-12-07 23:16:57 +00003422 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003423 unsigned CCInfo = Record[1];
3424 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3425 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003426
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003427 unsigned OpNum = 4;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003428 Value *Callee;
3429 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003430 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003431
Chris Lattner229907c2011-07-18 04:54:35 +00003432 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00003433 FunctionType *FTy = !CalleeTy ? nullptr :
Chris Lattner5285b5e2007-05-02 05:46:45 +00003434 dyn_cast<FunctionType>(CalleeTy->getElementType());
3435
3436 // Check that the right number of fixed parameters are here.
Craig Topper2617dcc2014-04-15 06:32:26 +00003437 if (!FTy || !NormalBB || !UnwindBB ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003438 Record.size() < OpNum+FTy->getNumParams())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003439 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003440
Chris Lattner5285b5e2007-05-02 05:46:45 +00003441 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003442 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003443 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3444 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003445 if (!Ops.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003446 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003447 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003448
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003449 if (!FTy->isVarArg()) {
3450 if (Record.size() != OpNum)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003451 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003452 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003453 // Read type/value pairs for varargs params.
3454 while (OpNum != Record.size()) {
3455 Value *Op;
3456 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003457 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003458 Ops.push_back(Op);
3459 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003460 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003461
Jay Foad5bd375a2011-07-15 08:37:34 +00003462 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00003463 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003464 cast<InvokeInst>(I)->setCallingConv(
3465 static_cast<CallingConv::ID>(CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00003466 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003467 break;
3468 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00003469 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3470 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003471 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003472 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003473 return Error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00003474 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00003475 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003476 break;
3477 }
Chris Lattnere53603e2007-05-02 04:27:25 +00003478 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00003479 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00003480 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003481 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00003482 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00003483 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003484 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003485 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003486 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003487 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003488
Jay Foad52131342011-03-30 11:28:46 +00003489 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00003490 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003491
Chris Lattnere14cb882007-05-04 19:11:41 +00003492 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003493 Value *V;
3494 // With the new function encoding, it is possible that operands have
3495 // negative IDs (for forward references). Use a signed VBR
3496 // representation to keep the encoding small.
3497 if (UseRelativeIDs)
3498 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3499 else
3500 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00003501 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003502 if (!V || !BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003503 return Error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00003504 PN->addIncoming(V, BB);
3505 }
3506 I = PN;
3507 break;
3508 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003509
Bill Wendlingfae14752011-08-12 20:24:12 +00003510 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3511 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3512 unsigned Idx = 0;
3513 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003514 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003515 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003516 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003517 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003518 Value *PersFn = nullptr;
Bill Wendlingfae14752011-08-12 20:24:12 +00003519 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003520 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003521
3522 bool IsCleanup = !!Record[Idx++];
3523 unsigned NumClauses = Record[Idx++];
3524 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3525 LP->setCleanup(IsCleanup);
3526 for (unsigned J = 0; J != NumClauses; ++J) {
3527 LandingPadInst::ClauseType CT =
3528 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3529 Value *Val;
3530
3531 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3532 delete LP;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003533 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003534 }
3535
3536 assert((CT != LandingPadInst::Catch ||
3537 !isa<ArrayType>(Val->getType())) &&
3538 "Catch clause has a invalid type!");
3539 assert((CT != LandingPadInst::Filter ||
3540 isa<ArrayType>(Val->getType())) &&
3541 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00003542 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00003543 }
3544
3545 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00003546 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00003547 break;
3548 }
3549
Chris Lattnerf1c87102011-06-17 18:09:11 +00003550 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3551 if (Record.size() != 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003552 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003553 PointerType *Ty =
Chris Lattnerc332bba2007-05-03 18:58:09 +00003554 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattner229907c2011-07-18 04:54:35 +00003555 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerf1c87102011-06-17 18:09:11 +00003556 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00003557 uint64_t AlignRecord = Record[3];
3558 const uint64_t InAllocaMask = uint64_t(1) << 5;
3559 bool InAlloca = AlignRecord & InAllocaMask;
3560 unsigned Align;
3561 if (std::error_code EC =
3562 parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
3563 return EC;
3564 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00003565 if (!Ty || !Size)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003566 return Error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00003567 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00003568 AI->setUsedWithInAlloca(InAlloca);
3569 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00003570 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00003571 break;
3572 }
Chris Lattner9f600c52007-05-03 22:04:19 +00003573 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003574 unsigned OpNum = 0;
3575 Value *Op;
3576 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00003577 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003578 return Error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00003579
3580 Type *Ty = nullptr;
3581 if (OpNum + 3 == Record.size())
3582 Ty = getTypeByID(Record[OpNum++]);
3583
JF Bastien30bf96b2015-02-22 19:32:03 +00003584 unsigned Align;
3585 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3586 return EC;
3587 I = new LoadInst(Op, "", Record[OpNum+1], Align);
David Blaikie85035652015-02-25 01:07:20 +00003588
3589 assert((!Ty || Ty == I->getType()) &&
3590 "Explicit type doesn't match pointee type of the first operand");
3591
Devang Patelaf206b82009-09-18 19:26:43 +00003592 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00003593 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00003594 }
Eli Friedman59b66882011-08-09 23:02:53 +00003595 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3596 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3597 unsigned OpNum = 0;
3598 Value *Op;
3599 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00003600 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003601 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003602
David Blaikie85035652015-02-25 01:07:20 +00003603 Type *Ty = nullptr;
3604 if (OpNum + 5 == Record.size())
3605 Ty = getTypeByID(Record[OpNum++]);
3606
Eli Friedman59b66882011-08-09 23:02:53 +00003607 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3608 if (Ordering == NotAtomic || Ordering == Release ||
3609 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003610 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003611 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003612 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003613 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3614
JF Bastien30bf96b2015-02-22 19:32:03 +00003615 unsigned Align;
3616 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3617 return EC;
3618 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00003619
3620 assert((!Ty || Ty == I->getType()) &&
3621 "Explicit type doesn't match pointee type of the first operand");
3622
Eli Friedman59b66882011-08-09 23:02:53 +00003623 InstructionList.push_back(I);
3624 break;
3625 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003626 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003627 unsigned OpNum = 0;
3628 Value *Val, *Ptr;
3629 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003630 popValue(Record, OpNum, NextValueNo,
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003631 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3632 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003633 return Error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00003634 unsigned Align;
3635 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3636 return EC;
3637 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00003638 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003639 break;
3640 }
Eli Friedman59b66882011-08-09 23:02:53 +00003641 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3642 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3643 unsigned OpNum = 0;
3644 Value *Val, *Ptr;
3645 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003646 popValue(Record, OpNum, NextValueNo,
Eli Friedman59b66882011-08-09 23:02:53 +00003647 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3648 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003649 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003650
3651 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00003652 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00003653 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003654 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003655 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3656 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003657 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003658
JF Bastien30bf96b2015-02-22 19:32:03 +00003659 unsigned Align;
3660 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3661 return EC;
3662 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00003663 InstructionList.push_back(I);
3664 break;
3665 }
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003666 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00003667 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00003668 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003669 unsigned OpNum = 0;
3670 Value *Ptr, *Cmp, *New;
3671 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003672 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003673 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003674 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003675 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
Tim Northover420a2162014-06-13 14:24:07 +00003676 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003677 return Error("Invalid record");
Tim Northovere94a5182014-03-11 10:48:52 +00003678 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3679 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003680 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003681 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
Tim Northovere94a5182014-03-11 10:48:52 +00003682
3683 AtomicOrdering FailureOrdering;
3684 if (Record.size() < 7)
3685 FailureOrdering =
3686 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3687 else
3688 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3689
3690 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3691 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003692 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00003693
3694 if (Record.size() < 8) {
3695 // Before weak cmpxchgs existed, the instruction simply returned the
3696 // value loaded from memory, so bitcode files from that era will be
3697 // expecting the first component of a modern cmpxchg.
3698 CurBB->getInstList().push_back(I);
3699 I = ExtractValueInst::Create(I, 0);
3700 } else {
3701 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3702 }
3703
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003704 InstructionList.push_back(I);
3705 break;
3706 }
3707 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3708 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3709 unsigned OpNum = 0;
3710 Value *Ptr, *Val;
3711 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003712 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003713 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3714 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003715 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003716 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3717 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3718 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003719 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003720 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman59b66882011-08-09 23:02:53 +00003721 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003722 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003723 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3724 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3725 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3726 InstructionList.push_back(I);
3727 break;
3728 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00003729 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3730 if (2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003731 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00003732 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3733 if (Ordering == NotAtomic || Ordering == Unordered ||
3734 Ordering == Monotonic)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003735 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00003736 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3737 I = new FenceInst(Context, Ordering, SynchScope);
3738 InstructionList.push_back(I);
3739 break;
3740 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003741 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003742 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3743 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003744 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003745
Bill Wendlinge94d8432012-12-07 23:16:57 +00003746 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003747 unsigned CCInfo = Record[1];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003748
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003749 unsigned OpNum = 2;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003750 Value *Callee;
3751 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003752 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003753
Chris Lattner229907c2011-07-18 04:54:35 +00003754 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00003755 FunctionType *FTy = nullptr;
Chris Lattner9f600c52007-05-03 22:04:19 +00003756 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003757 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003758 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003759
Chris Lattner9f600c52007-05-03 22:04:19 +00003760 SmallVector<Value*, 16> Args;
3761 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003762 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003763 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00003764 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00003765 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00003766 Args.push_back(getValue(Record, OpNum, NextValueNo,
3767 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003768 if (!Args.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003769 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00003770 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003771
Chris Lattner9f600c52007-05-03 22:04:19 +00003772 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00003773 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003774 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003775 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00003776 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003777 while (OpNum != Record.size()) {
3778 Value *Op;
3779 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003780 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003781 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00003782 }
3783 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003784
Jay Foad5bd375a2011-07-15 08:37:34 +00003785 I = CallInst::Create(Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00003786 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003787 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00003788 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3789 CallInst::TailCallKind TCK = CallInst::TCK_None;
3790 if (CCInfo & 1)
3791 TCK = CallInst::TCK_Tail;
3792 if (CCInfo & (1 << 14))
3793 TCK = CallInst::TCK_MustTail;
3794 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00003795 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00003796 break;
3797 }
3798 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3799 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003800 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003801 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003802 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003803 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00003804 if (!OpTy || !Op || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003805 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00003806 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00003807 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00003808 break;
3809 }
Chris Lattner83930552007-05-01 07:01:57 +00003810 }
3811
3812 // Add instruction to end of current BB. If there is no current BB, reject
3813 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00003814 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00003815 delete I;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003816 return Error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00003817 }
3818 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003819
Chris Lattner83930552007-05-01 07:01:57 +00003820 // If this was a terminator instruction, move to the next block.
3821 if (isa<TerminatorInst>(I)) {
3822 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00003823 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00003824 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003825
Chris Lattner83930552007-05-01 07:01:57 +00003826 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003827 if (I && !I->getType()->isVoidTy())
Chris Lattner83930552007-05-01 07:01:57 +00003828 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00003829 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003830
Chris Lattner27d38752013-01-20 02:13:19 +00003831OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00003832
Chris Lattner83930552007-05-01 07:01:57 +00003833 // Check the function list for unresolved values.
3834 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003835 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00003836 // We found at least one unresolved value. Nuke them all to avoid leaks.
3837 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00003838 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003839 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00003840 delete A;
3841 }
3842 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003843 return Error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00003844 }
Chris Lattner83930552007-05-01 07:01:57 +00003845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003846
Dan Gohman9b9ff462010-08-25 20:23:38 +00003847 // FIXME: Check for unresolved forward-declared metadata references
3848 // and clean up leaks.
3849
Chris Lattner85b7b402007-05-01 05:52:21 +00003850 // Trim the value list down to the size it was before we parsed this function.
3851 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00003852 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00003853 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003854 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003855}
3856
Rafael Espindola7d712032013-11-05 17:16:08 +00003857/// Find the function body in the bitcode stream
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003858std::error_code BitcodeReader::FindFunctionInStream(
3859 Function *F,
3860 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003861 while (DeferredFunctionInfoIterator->second == 0) {
3862 if (Stream.AtEndOfStream())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003863 return Error("Could not find function in stream");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003864 // ParseModule will parse the next body in the stream and set its
3865 // position in the DeferredFunctionInfo map.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003866 if (std::error_code EC = ParseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00003867 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003868 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003869 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003870}
3871
Chris Lattner9eeada92007-05-18 04:02:46 +00003872//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003873// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00003874//===----------------------------------------------------------------------===//
3875
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00003876void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00003877
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00003878std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003879 Function *F = dyn_cast<Function>(GV);
3880 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003881 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003882 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003883
3884 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00003885 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003886 // If its position is recorded as 0, its body is somewhere in the stream
3887 // but we haven't seen it yet.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003888 if (DFII->second == 0 && LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003889 if (std::error_code EC = FindFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003890 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003891
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003892 // Move the bit stream to the saved position of the deferred function body.
3893 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003894
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003895 if (std::error_code EC = ParseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003896 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003897 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00003898
3899 // Upgrade any old intrinsic calls in the function.
3900 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3901 E = UpgradedIntrinsics.end(); I != E; ++I) {
3902 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003903 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3904 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003905 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3906 UpgradeIntrinsicCall(CI, I->second);
3907 }
3908 }
3909 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003910
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003911 // Bring in any functions that this function forward-referenced via
3912 // blockaddresses.
3913 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00003914}
3915
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003916bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3917 const Function *F = dyn_cast<Function>(GV);
3918 if (!F || F->isDeclaration())
3919 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003920
3921 // Dematerializing F would leave dangling references that wouldn't be
3922 // reconnected on re-materialization.
3923 if (BlockAddressesTaken.count(F))
3924 return false;
3925
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003926 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3927}
3928
3929void BitcodeReader::Dematerialize(GlobalValue *GV) {
3930 Function *F = dyn_cast<Function>(GV);
3931 // If this function isn't dematerializable, this is a noop.
3932 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00003933 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003934
Chris Lattner9eeada92007-05-18 04:02:46 +00003935 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003936
Chris Lattner9eeada92007-05-18 04:02:46 +00003937 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00003938 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003939 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00003940}
3941
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003942std::error_code BitcodeReader::MaterializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003943 assert(M == TheModule &&
3944 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003945
3946 // Promise to materialize all forward references.
3947 WillMaterializeAllForwardRefs = true;
3948
Chris Lattner06310bf2009-06-16 05:15:21 +00003949 // Iterate over the module, deserializing any functions that are still on
3950 // disk.
3951 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003952 F != E; ++F) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +00003953 if (std::error_code EC = materialize(F))
3954 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003955 }
Derek Schuff92ef9752012-02-29 00:07:09 +00003956 // At this point, if there are any function bodies, the current bit is
3957 // pointing to the END_BLOCK record after them. Now make sure the rest
3958 // of the bits in the module have been read.
3959 if (NextUnreadBit)
3960 ParseModule(true);
3961
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003962 // Check that all block address forward references got resolved (as we
3963 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003964 if (!BasicBlockFwdRefs.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003965 return Error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003966
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003967 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3968 // delete the old functions to clean up. We can't do this unless the entire
3969 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00003970 // with calls to the old function.
3971 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3972 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3973 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003974 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3975 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003976 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3977 UpgradeIntrinsicCall(CI, I->second);
3978 }
Chris Lattner647cffb2009-04-01 01:43:03 +00003979 if (!I->first->use_empty())
3980 I->first->replaceAllUsesWith(I->second);
Chandler Carruth7132e002007-08-04 01:51:18 +00003981 I->first->eraseFromParent();
3982 }
3983 }
3984 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patel80ae3492009-08-28 23:24:31 +00003985
Manman Ren209b17c2013-09-28 00:22:27 +00003986 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3987 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3988
Manman Ren8b4306c2013-12-02 21:29:56 +00003989 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003990 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00003991}
3992
Rafael Espindola2fa1e432014-12-03 07:18:23 +00003993std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3994 return IdentifiedStructTypes;
3995}
3996
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003997std::error_code BitcodeReader::InitStream() {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003998 if (LazyStreamer)
3999 return InitLazyStream();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004000 return InitStreamFromBuffer();
4001}
4002
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004003std::error_code BitcodeReader::InitStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00004004 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004005 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4006
Rafael Espindola27435252014-07-29 21:01:24 +00004007 if (Buffer->getBufferSize() & 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004008 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004009
4010 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4011 // The magic number is 0x0B17C0DE stored in little endian.
4012 if (isBitcodeWrapper(BufPtr, BufEnd))
4013 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004014 return Error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004015
4016 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004017 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004018
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004019 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004020}
4021
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004022std::error_code BitcodeReader::InitLazyStream() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004023 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4024 // see it.
Yaron Keren06d69302014-12-18 10:03:35 +00004025 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004026 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00004027 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004028 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004029
4030 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00004031 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004032 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004033
4034 if (!isBitcode(buf, buf + 16))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004035 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004036
4037 if (isBitcodeWrapper(buf, buf + 4)) {
4038 const unsigned char *bitcodeStart = buf;
4039 const unsigned char *bitcodeEnd = buf + 16;
4040 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004041 Bytes.dropLeadingBytes(bitcodeStart - buf);
4042 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004043 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004044 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00004045}
4046
4047namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00004048class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00004049 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00004050 return "llvm.bitcode";
4051 }
Craig Topper73156022014-03-02 09:09:27 +00004052 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004053 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004054 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004055 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00004056 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004057 case BitcodeError::CorruptedBitcode:
4058 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00004059 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00004060 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00004061 }
4062};
4063}
4064
Chris Bieneman770163e2014-09-19 20:29:02 +00004065static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4066
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004067const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00004068 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004069}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004070
Chris Lattner6694f602007-04-29 07:54:31 +00004071//===----------------------------------------------------------------------===//
4072// External interface
4073//===----------------------------------------------------------------------===//
4074
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004075/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00004076///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004077/// This isn't always used in a lazy context. In particular, it's also used by
4078/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4079/// in forward-referenced functions from block address references.
4080///
4081/// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4082/// materialize everything -- in particular, if this isn't truly lazy.
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004083static ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00004084getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004085 LLVMContext &Context, bool WillMaterializeAll,
4086 DiagnosticHandlerFunction DiagnosticHandler) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004087 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004088 BitcodeReader *R =
4089 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004090 M->setMaterializer(R);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004091
4092 auto cleanupOnError = [&](std::error_code EC) {
Rafael Espindola8fb31112014-06-18 20:07:35 +00004093 R->releaseBuffer(); // Never take ownership on error.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004094 delete M; // Also deletes R.
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00004095 return EC;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004096 };
Rafael Espindolab7993462012-01-02 07:49:53 +00004097
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004098 if (std::error_code EC = R->ParseBitcodeInto(M))
4099 return cleanupOnError(EC);
4100
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004101 if (!WillMaterializeAll)
4102 // Resolve forward references from blockaddresses.
4103 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4104 return cleanupOnError(EC);
Rafael Espindolab7993462012-01-02 07:49:53 +00004105
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004106 Buffer.release(); // The BitcodeReader owns it now.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004107 return M;
Chris Lattner6694f602007-04-29 07:54:31 +00004108}
4109
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004110ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00004111llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004112 LLVMContext &Context,
4113 DiagnosticHandlerFunction DiagnosticHandler) {
4114 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4115 DiagnosticHandler);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004116}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004117
Rafael Espindola7d727b52014-12-18 05:08:43 +00004118ErrorOr<std::unique_ptr<Module>>
4119llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004120 LLVMContext &Context,
4121 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00004122 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004123 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004124 M->setMaterializer(R);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004125 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4126 return EC;
4127 return std::move(M);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004128}
4129
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004130ErrorOr<Module *>
4131llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4132 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004133 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004134 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4135 std::move(Buf), Context, true, DiagnosticHandler);
Rafael Espindola8f31e212014-01-15 01:08:23 +00004136 if (!ModuleOrErr)
4137 return ModuleOrErr;
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00004138 Module *M = ModuleOrErr.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004139 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolad96d5532014-08-26 21:49:01 +00004140 if (std::error_code EC = M->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004141 delete M;
Rafael Espindola8f31e212014-01-15 01:08:23 +00004142 return EC;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004143 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004144
Chad Rosierca2567b2011-12-07 21:44:12 +00004145 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4146 // written. We must defer until the Module has been fully materialized.
4147
Chris Lattner6694f602007-04-29 07:54:31 +00004148 return M;
4149}
Bill Wendling0198ce02010-10-06 01:22:42 +00004150
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004151std::string
4152llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4153 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004154 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004155 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4156 DiagnosticHandler);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004157 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00004158 if (Triple.getError())
4159 return "";
4160 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00004161}