blob: 75d311c038649b2e05eec9e1e17efa288a5688e2 [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"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000014#include "llvm/Bitcode/LLVMBitCodes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000015#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
17#include "llvm/IR/DerivedTypes.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000018#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/InlineAsm.h"
20#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000021#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Module.h"
23#include "llvm/IR/OperandTraits.h"
24#include "llvm/IR/Operator.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000025#include "llvm/Support/DataStream.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000028#include "llvm/Support/raw_ostream.h"
Chris Bieneman770163e2014-09-19 20:29:02 +000029#include "llvm/Support/ManagedStatic.h"
30
Chris Lattner1314b992007-04-22 06:23:29 +000031using namespace llvm;
32
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000033enum {
34 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
35};
36
Rafael Espindolad0b23be2015-01-10 00:07:30 +000037BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
38 DiagnosticSeverity Severity,
39 const Twine &Msg)
40 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
41
42void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
43
44static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
45 std::error_code EC, const Twine &Message) {
46 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
47 DiagnosticHandler(DI);
48 return EC;
49}
50
51static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
52 std::error_code EC) {
53 return Error(DiagnosticHandler, EC, EC.message());
54}
55
56std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
57 return ::Error(DiagnosticHandler, make_error_code(E), Message);
58}
59
60std::error_code BitcodeReader::Error(const Twine &Message) {
61 return ::Error(DiagnosticHandler,
62 make_error_code(BitcodeError::CorruptedBitcode), Message);
63}
64
65std::error_code BitcodeReader::Error(BitcodeError E) {
66 return ::Error(DiagnosticHandler, make_error_code(E));
67}
68
69static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
70 LLVMContext &C) {
71 if (F)
72 return F;
73 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
74}
75
76BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
77 DiagnosticHandlerFunction DiagnosticHandler)
78 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
79 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
80 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
81 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
82 WillMaterializeAllForwardRefs(false) {}
83
84BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
85 DiagnosticHandlerFunction DiagnosticHandler)
86 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
87 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
88 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
89 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
90 WillMaterializeAllForwardRefs(false) {}
91
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000092std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
93 if (WillMaterializeAllForwardRefs)
94 return std::error_code();
95
96 // Prevent recursion.
97 WillMaterializeAllForwardRefs = true;
98
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000099 while (!BasicBlockFwdRefQueue.empty()) {
100 Function *F = BasicBlockFwdRefQueue.front();
101 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000102 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000103 if (!BasicBlockFwdRefs.count(F))
104 // Already materialized.
105 continue;
106
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000107 // Check for a function that isn't materializable to prevent an infinite
108 // loop. When parsing a blockaddress stored in a global variable, there
109 // isn't a trivial way to check if a function will have a body without a
110 // linear search through FunctionsWithBodies, so just check it here.
111 if (!F->isMaterializable())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000112 return Error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000113
114 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000115 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000116 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000117 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000118 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000119
120 // Reset state.
121 WillMaterializeAllForwardRefs = false;
122 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000123}
124
Chris Lattner9eeada92007-05-18 04:02:46 +0000125void BitcodeReader::FreeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000126 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000127 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000128 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +0000129 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000130 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000131
Bill Wendlinge94d8432012-12-07 23:16:57 +0000132 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000133 std::vector<BasicBlock*>().swap(FunctionBBs);
134 std::vector<Function*>().swap(FunctionsWithBodies);
135 DeferredFunctionInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000136 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000137
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000138 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000139 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000140}
141
Chris Lattnerfee5a372007-05-04 03:30:17 +0000142//===----------------------------------------------------------------------===//
143// Helper functions to implement forward reference resolution, etc.
144//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000145
Chris Lattner1314b992007-04-22 06:23:29 +0000146/// ConvertToString - Convert a string from a record into an std::string, return
147/// true on failure.
Chris Lattnerccaa4482007-04-23 21:26:05 +0000148template<typename StrTy>
Benjamin Kramer9704ed02012-05-28 14:10:31 +0000149static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000150 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000151 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000152 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000153
Chris Lattnere14cb882007-05-04 19:11:41 +0000154 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
155 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000156 return false;
157}
158
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000159static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000160 switch (Val) {
161 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000162 case 0:
163 return GlobalValue::ExternalLinkage;
164 case 1:
165 return GlobalValue::WeakAnyLinkage;
166 case 2:
167 return GlobalValue::AppendingLinkage;
168 case 3:
169 return GlobalValue::InternalLinkage;
170 case 4:
171 return GlobalValue::LinkOnceAnyLinkage;
172 case 5:
173 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
174 case 6:
175 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
176 case 7:
177 return GlobalValue::ExternalWeakLinkage;
178 case 8:
179 return GlobalValue::CommonLinkage;
180 case 9:
181 return GlobalValue::PrivateLinkage;
182 case 10:
183 return GlobalValue::WeakODRLinkage;
184 case 11:
185 return GlobalValue::LinkOnceODRLinkage;
186 case 12:
187 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000188 case 13:
189 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
190 case 14:
191 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000192 case 15:
193 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Chris Lattner1314b992007-04-22 06:23:29 +0000194 }
195}
196
197static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
198 switch (Val) {
199 default: // Map unknown visibilities to default.
200 case 0: return GlobalValue::DefaultVisibility;
201 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000202 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000203 }
204}
205
Nico Rieck7157bb72014-01-14 15:22:47 +0000206static GlobalValue::DLLStorageClassTypes
207GetDecodedDLLStorageClass(unsigned Val) {
208 switch (Val) {
209 default: // Map unknown values to default.
210 case 0: return GlobalValue::DefaultStorageClass;
211 case 1: return GlobalValue::DLLImportStorageClass;
212 case 2: return GlobalValue::DLLExportStorageClass;
213 }
214}
215
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000216static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
217 switch (Val) {
218 case 0: return GlobalVariable::NotThreadLocal;
219 default: // Map unknown non-zero value to general dynamic.
220 case 1: return GlobalVariable::GeneralDynamicTLSModel;
221 case 2: return GlobalVariable::LocalDynamicTLSModel;
222 case 3: return GlobalVariable::InitialExecTLSModel;
223 case 4: return GlobalVariable::LocalExecTLSModel;
224 }
225}
226
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000227static int GetDecodedCastOpcode(unsigned Val) {
228 switch (Val) {
229 default: return -1;
230 case bitc::CAST_TRUNC : return Instruction::Trunc;
231 case bitc::CAST_ZEXT : return Instruction::ZExt;
232 case bitc::CAST_SEXT : return Instruction::SExt;
233 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
234 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
235 case bitc::CAST_UITOFP : return Instruction::UIToFP;
236 case bitc::CAST_SITOFP : return Instruction::SIToFP;
237 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
238 case bitc::CAST_FPEXT : return Instruction::FPExt;
239 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
240 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
241 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000242 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000243 }
244}
Chris Lattner229907c2011-07-18 04:54:35 +0000245static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000246 switch (Val) {
247 default: return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000248 case bitc::BINOP_ADD:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000249 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000250 case bitc::BINOP_SUB:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000251 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000252 case bitc::BINOP_MUL:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000253 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000254 case bitc::BINOP_UDIV: return Instruction::UDiv;
255 case bitc::BINOP_SDIV:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000256 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000257 case bitc::BINOP_UREM: return Instruction::URem;
258 case bitc::BINOP_SREM:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000259 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000260 case bitc::BINOP_SHL: return Instruction::Shl;
261 case bitc::BINOP_LSHR: return Instruction::LShr;
262 case bitc::BINOP_ASHR: return Instruction::AShr;
263 case bitc::BINOP_AND: return Instruction::And;
264 case bitc::BINOP_OR: return Instruction::Or;
265 case bitc::BINOP_XOR: return Instruction::Xor;
266 }
267}
268
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000269static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
270 switch (Val) {
271 default: return AtomicRMWInst::BAD_BINOP;
272 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
273 case bitc::RMW_ADD: return AtomicRMWInst::Add;
274 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
275 case bitc::RMW_AND: return AtomicRMWInst::And;
276 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
277 case bitc::RMW_OR: return AtomicRMWInst::Or;
278 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
279 case bitc::RMW_MAX: return AtomicRMWInst::Max;
280 case bitc::RMW_MIN: return AtomicRMWInst::Min;
281 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
282 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
283 }
284}
285
Eli Friedmanfee02c62011-07-25 23:16:38 +0000286static AtomicOrdering GetDecodedOrdering(unsigned Val) {
287 switch (Val) {
288 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
289 case bitc::ORDERING_UNORDERED: return Unordered;
290 case bitc::ORDERING_MONOTONIC: return Monotonic;
291 case bitc::ORDERING_ACQUIRE: return Acquire;
292 case bitc::ORDERING_RELEASE: return Release;
293 case bitc::ORDERING_ACQREL: return AcquireRelease;
294 default: // Map unknown orderings to sequentially-consistent.
295 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
296 }
297}
298
299static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
300 switch (Val) {
301 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
302 default: // Map unknown scopes to cross-thread.
303 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
304 }
305}
306
David Majnemerdad0a642014-06-27 18:19:56 +0000307static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
308 switch (Val) {
309 default: // Map unknown selection kinds to any.
310 case bitc::COMDAT_SELECTION_KIND_ANY:
311 return Comdat::Any;
312 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
313 return Comdat::ExactMatch;
314 case bitc::COMDAT_SELECTION_KIND_LARGEST:
315 return Comdat::Largest;
316 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
317 return Comdat::NoDuplicates;
318 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
319 return Comdat::SameSize;
320 }
321}
322
Nico Rieck7157bb72014-01-14 15:22:47 +0000323static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
324 switch (Val) {
325 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
326 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
327 }
328}
329
Gabor Greiff6caff662008-05-10 08:32:32 +0000330namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000331namespace {
332 /// @brief A class for maintaining the slot number definition
333 /// as a placeholder for the actual definition for forward constants defs.
334 class ConstantPlaceHolder : public ConstantExpr {
Craig Toppera60c0f12012-09-15 17:09:36 +0000335 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greife9ecc682008-04-06 20:25:17 +0000336 public:
337 // allocate space for exactly one operand
338 void *operator new(size_t s) {
339 return User::operator new(s, 1);
340 }
Chris Lattner229907c2011-07-18 04:54:35 +0000341 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000342 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000343 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner1663cca2007-04-24 05:48:56 +0000344 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000345
Chris Lattner74429932008-08-21 02:34:16 +0000346 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner74429932008-08-21 02:34:16 +0000347 static bool classof(const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000348 return isa<ConstantExpr>(V) &&
Chris Lattner74429932008-08-21 02:34:16 +0000349 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
350 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000351
352
Gabor Greiff6caff662008-05-10 08:32:32 +0000353 /// Provide fast operand accessors
Richard Trieue3d126c2014-11-21 02:42:08 +0000354 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner1663cca2007-04-24 05:48:56 +0000355 };
356}
357
Chris Lattner2d8cd802009-03-31 22:55:09 +0000358// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000359template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000360struct OperandTraits<ConstantPlaceHolder> :
361 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000362};
Richard Trieue3d126c2014-11-21 02:42:08 +0000363DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Gabor Greiff6caff662008-05-10 08:32:32 +0000364}
365
Chris Lattner2d8cd802009-03-31 22:55:09 +0000366
367void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
368 if (Idx == size()) {
369 push_back(V);
370 return;
371 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000372
Chris Lattner2d8cd802009-03-31 22:55:09 +0000373 if (Idx >= size())
374 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000375
Chris Lattner2d8cd802009-03-31 22:55:09 +0000376 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000377 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000378 OldV = V;
379 return;
380 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000381
Chris Lattner2d8cd802009-03-31 22:55:09 +0000382 // Handle constants and non-constants (e.g. instrs) differently for
383 // efficiency.
384 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
385 ResolveConstants.push_back(std::make_pair(PHC, Idx));
386 OldV = V;
387 } else {
388 // If there was a forward reference to this value, replace it.
389 Value *PrevVal = OldV;
390 OldV->replaceAllUsesWith(V);
391 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000392 }
393}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000394
Gabor Greiff6caff662008-05-10 08:32:32 +0000395
Chris Lattner1663cca2007-04-24 05:48:56 +0000396Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000397 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000398 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000399 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000400
Chris Lattner2d8cd802009-03-31 22:55:09 +0000401 if (Value *V = ValuePtrs[Idx]) {
Chris Lattner83930552007-05-01 07:01:57 +0000402 assert(Ty == V->getType() && "Type mismatch in constant table!");
403 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000404 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000405
406 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000407 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000408 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000409 return C;
410}
411
Chris Lattner229907c2011-07-18 04:54:35 +0000412Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000413 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000414 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000415
Chris Lattner2d8cd802009-03-31 22:55:09 +0000416 if (Value *V = ValuePtrs[Idx]) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000417 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
Chris Lattner83930552007-05-01 07:01:57 +0000418 return V;
419 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000420
Chris Lattner1fc27f02007-05-02 05:16:49 +0000421 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000422 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000423
Chris Lattner83930552007-05-01 07:01:57 +0000424 // Create and return a placeholder, which will later be RAUW'd.
425 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000426 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000427 return V;
428}
429
Chris Lattner74429932008-08-21 02:34:16 +0000430/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
431/// resolves any forward references. The idea behind this is that we sometimes
432/// get constants (such as large arrays) which reference *many* forward ref
433/// constants. Replacing each of these causes a lot of thrashing when
434/// building/reuniquing the constant. Instead of doing this, we look at all the
435/// uses and rewrite all the place holders at once for any constant that uses
436/// a placeholder.
437void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000438 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000439 // binary search.
440 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000441
Chris Lattner74429932008-08-21 02:34:16 +0000442 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000443
Chris Lattner74429932008-08-21 02:34:16 +0000444 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000445 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000446 Constant *Placeholder = ResolveConstants.back().first;
447 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000448
Chris Lattner74429932008-08-21 02:34:16 +0000449 // Loop over all users of the placeholder, updating them to reference the
450 // new value. If they reference more than one placeholder, update them all
451 // at once.
452 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000453 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000454 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000455
Chris Lattner74429932008-08-21 02:34:16 +0000456 // If the using object isn't uniqued, just update the operands. This
457 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000458 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000459 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000460 continue;
461 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000462
Chris Lattner74429932008-08-21 02:34:16 +0000463 // Otherwise, we have a constant that uses the placeholder. Replace that
464 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000465 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000466 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
467 I != E; ++I) {
468 Value *NewOp;
469 if (!isa<ConstantPlaceHolder>(*I)) {
470 // Not a placeholder reference.
471 NewOp = *I;
472 } else if (*I == Placeholder) {
473 // Common case is that it just references this one placeholder.
474 NewOp = RealVal;
475 } else {
476 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000477 ResolveConstantsTy::iterator It =
478 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000479 std::pair<Constant*, unsigned>(cast<Constant>(*I),
480 0));
481 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000482 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000483 }
484
485 NewOps.push_back(cast<Constant>(NewOp));
486 }
487
488 // Make the new constant.
489 Constant *NewC;
490 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000491 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000492 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000493 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000494 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000495 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000496 } else {
497 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000498 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000499 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Chris Lattner74429932008-08-21 02:34:16 +0000501 UserC->replaceAllUsesWith(NewC);
502 UserC->destroyConstant();
503 NewOps.clear();
504 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000505
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000506 // Update all ValueHandles, they should be the only users at this point.
507 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000508 delete Placeholder;
509 }
510}
511
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000512void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000513 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000514 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000515 return;
516 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000517
Devang Patel05eb6172009-08-04 06:00:18 +0000518 if (Idx >= size())
519 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000520
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000521 TrackingMDRef &OldMD = MDValuePtrs[Idx];
522 if (!OldMD) {
523 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000524 return;
525 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000526
Devang Patel05eb6172009-08-04 06:00:18 +0000527 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000528 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
529 PrevMD->replaceAllUsesWith(MD);
530 MDNode::deleteTemporary(PrevMD);
531 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +0000532}
533
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000534Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000535 if (Idx >= size())
536 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000537
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000538 if (Metadata *MD = MDValuePtrs[Idx])
539 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000540
Devang Patel05eb6172009-08-04 06:00:18 +0000541 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000542 AnyFwdRefs = true;
543 ++NumFwdRefs;
544 Metadata *MD = MDNode::getTemporary(Context, None);
545 MDValuePtrs[Idx].reset(MD);
546 return MD;
547}
548
549void BitcodeReaderMDValueList::tryToResolveCycles() {
550 if (!AnyFwdRefs)
551 // Nothing to do.
552 return;
553
554 if (NumFwdRefs)
555 // Still forward references... can't resolve cycles.
556 return;
557
558 // Resolve any cycles.
559 for (auto &MD : MDValuePtrs) {
560 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
561 if (auto *G = dyn_cast_or_null<GenericMDNode>(MD))
562 G->resolveCycles();
563 }
Devang Patel05eb6172009-08-04 06:00:18 +0000564}
Chris Lattner1314b992007-04-22 06:23:29 +0000565
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000566Type *BitcodeReader::getTypeByID(unsigned ID) {
567 // The type table size is always specified correctly.
568 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +0000569 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +0000570
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000571 if (Type *Ty = TypeList[ID])
572 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000573
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000574 // If we have a forward reference, the only possible case is when it is to a
575 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000576 return TypeList[ID] = createIdentifiedStructType(Context);
577}
578
579StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
580 StringRef Name) {
581 auto *Ret = StructType::create(Context, Name);
582 IdentifiedStructTypes.push_back(Ret);
583 return Ret;
584}
585
586StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
587 auto *Ret = StructType::create(Context);
588 IdentifiedStructTypes.push_back(Ret);
589 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +0000590}
591
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000592
Chris Lattnerfee5a372007-05-04 03:30:17 +0000593//===----------------------------------------------------------------------===//
594// Functions for parsing blocks from the bitcode file
595//===----------------------------------------------------------------------===//
596
Bill Wendling56aeccc2013-02-04 23:32:23 +0000597
598/// \brief This fills an AttrBuilder object with the LLVM attributes that have
599/// been decoded from the given integer. This function must stay in sync with
600/// 'encodeLLVMAttributesForBitcode'.
601static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
602 uint64_t EncodedAttrs) {
603 // FIXME: Remove in 4.0.
604
605 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
606 // the bits above 31 down by 11 bits.
607 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
608 assert((!Alignment || isPowerOf2_32(Alignment)) &&
609 "Alignment must be a power of two.");
610
611 if (Alignment)
612 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +0000613 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +0000614 (EncodedAttrs & 0xffff));
615}
616
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000617std::error_code BitcodeReader::ParseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +0000618 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000619 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000620
Devang Patela05633e2008-09-26 22:53:05 +0000621 if (!MAttributes.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000622 return Error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000623
Chris Lattnerfee5a372007-05-04 03:30:17 +0000624 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000625
Bill Wendling71173cb2013-01-27 00:36:48 +0000626 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000627
Chris Lattnerfee5a372007-05-04 03:30:17 +0000628 // Read all the records.
629 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000630 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000631
Chris Lattner27d38752013-01-20 02:13:19 +0000632 switch (Entry.Kind) {
633 case BitstreamEntry::SubBlock: // Handled for us already.
634 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000635 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +0000636 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000637 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000638 case BitstreamEntry::Record:
639 // The interesting case.
640 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +0000641 }
Joe Abbey97b7a172013-02-06 22:14:06 +0000642
Chris Lattnerfee5a372007-05-04 03:30:17 +0000643 // Read a record.
644 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +0000645 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +0000646 default: // Default behavior: ignore.
647 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000648 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
649 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +0000650 if (Record.size() & 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000651 return Error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +0000652
Chris Lattnerfee5a372007-05-04 03:30:17 +0000653 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +0000654 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000655 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +0000656 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +0000657 }
Devang Patela05633e2008-09-26 22:53:05 +0000658
Bill Wendlinge94d8432012-12-07 23:16:57 +0000659 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +0000660 Attrs.clear();
661 break;
662 }
Bill Wendling0dc08912013-02-12 08:13:50 +0000663 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
664 for (unsigned i = 0, e = Record.size(); i != e; ++i)
665 Attrs.push_back(MAttributeGroups[Record[i]]);
666
667 MAttributes.push_back(AttributeSet::get(Context, Attrs));
668 Attrs.clear();
669 break;
670 }
Duncan Sands04eb67e2007-11-20 14:09:29 +0000671 }
Chris Lattnerfee5a372007-05-04 03:30:17 +0000672 }
673}
674
Reid Klecknere9f36af2013-11-12 01:31:00 +0000675// Returns Attribute::None on unrecognized codes.
676static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
677 switch (Code) {
678 default:
679 return Attribute::None;
680 case bitc::ATTR_KIND_ALIGNMENT:
681 return Attribute::Alignment;
682 case bitc::ATTR_KIND_ALWAYS_INLINE:
683 return Attribute::AlwaysInline;
684 case bitc::ATTR_KIND_BUILTIN:
685 return Attribute::Builtin;
686 case bitc::ATTR_KIND_BY_VAL:
687 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +0000688 case bitc::ATTR_KIND_IN_ALLOCA:
689 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000690 case bitc::ATTR_KIND_COLD:
691 return Attribute::Cold;
692 case bitc::ATTR_KIND_INLINE_HINT:
693 return Attribute::InlineHint;
694 case bitc::ATTR_KIND_IN_REG:
695 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000696 case bitc::ATTR_KIND_JUMP_TABLE:
697 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000698 case bitc::ATTR_KIND_MIN_SIZE:
699 return Attribute::MinSize;
700 case bitc::ATTR_KIND_NAKED:
701 return Attribute::Naked;
702 case bitc::ATTR_KIND_NEST:
703 return Attribute::Nest;
704 case bitc::ATTR_KIND_NO_ALIAS:
705 return Attribute::NoAlias;
706 case bitc::ATTR_KIND_NO_BUILTIN:
707 return Attribute::NoBuiltin;
708 case bitc::ATTR_KIND_NO_CAPTURE:
709 return Attribute::NoCapture;
710 case bitc::ATTR_KIND_NO_DUPLICATE:
711 return Attribute::NoDuplicate;
712 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
713 return Attribute::NoImplicitFloat;
714 case bitc::ATTR_KIND_NO_INLINE:
715 return Attribute::NoInline;
716 case bitc::ATTR_KIND_NON_LAZY_BIND:
717 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000718 case bitc::ATTR_KIND_NON_NULL:
719 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000720 case bitc::ATTR_KIND_DEREFERENCEABLE:
721 return Attribute::Dereferenceable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000722 case bitc::ATTR_KIND_NO_RED_ZONE:
723 return Attribute::NoRedZone;
724 case bitc::ATTR_KIND_NO_RETURN:
725 return Attribute::NoReturn;
726 case bitc::ATTR_KIND_NO_UNWIND:
727 return Attribute::NoUnwind;
728 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
729 return Attribute::OptimizeForSize;
730 case bitc::ATTR_KIND_OPTIMIZE_NONE:
731 return Attribute::OptimizeNone;
732 case bitc::ATTR_KIND_READ_NONE:
733 return Attribute::ReadNone;
734 case bitc::ATTR_KIND_READ_ONLY:
735 return Attribute::ReadOnly;
736 case bitc::ATTR_KIND_RETURNED:
737 return Attribute::Returned;
738 case bitc::ATTR_KIND_RETURNS_TWICE:
739 return Attribute::ReturnsTwice;
740 case bitc::ATTR_KIND_S_EXT:
741 return Attribute::SExt;
742 case bitc::ATTR_KIND_STACK_ALIGNMENT:
743 return Attribute::StackAlignment;
744 case bitc::ATTR_KIND_STACK_PROTECT:
745 return Attribute::StackProtect;
746 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
747 return Attribute::StackProtectReq;
748 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
749 return Attribute::StackProtectStrong;
750 case bitc::ATTR_KIND_STRUCT_RET:
751 return Attribute::StructRet;
752 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
753 return Attribute::SanitizeAddress;
754 case bitc::ATTR_KIND_SANITIZE_THREAD:
755 return Attribute::SanitizeThread;
756 case bitc::ATTR_KIND_SANITIZE_MEMORY:
757 return Attribute::SanitizeMemory;
758 case bitc::ATTR_KIND_UW_TABLE:
759 return Attribute::UWTable;
760 case bitc::ATTR_KIND_Z_EXT:
761 return Attribute::ZExt;
762 }
763}
764
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000765std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
766 Attribute::AttrKind *Kind) {
Reid Klecknere9f36af2013-11-12 01:31:00 +0000767 *Kind = GetAttrFromCode(Code);
768 if (*Kind == Attribute::None)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000769 return Error(BitcodeError::CorruptedBitcode,
770 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000771 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000772}
773
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000774std::error_code BitcodeReader::ParseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +0000775 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000776 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +0000777
778 if (!MAttributeGroups.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000779 return Error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +0000780
781 SmallVector<uint64_t, 64> Record;
782
783 // Read all the records.
784 while (1) {
785 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
786
787 switch (Entry.Kind) {
788 case BitstreamEntry::SubBlock: // Handled for us already.
789 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000790 return Error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +0000791 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000792 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +0000793 case BitstreamEntry::Record:
794 // The interesting case.
795 break;
796 }
797
798 // Read a record.
799 Record.clear();
800 switch (Stream.readRecord(Entry.ID, Record)) {
801 default: // Default behavior: ignore.
802 break;
803 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
804 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000805 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +0000806
Bill Wendlinge46707e2013-02-11 22:32:29 +0000807 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +0000808 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
809
810 AttrBuilder B;
811 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
812 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000813 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000814 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000815 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000816
817 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +0000818 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000819 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000820 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000821 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000822 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000823 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000824 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000825 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000826 else if (Kind == Attribute::Dereferenceable)
827 B.addDereferenceableAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +0000828 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +0000829 assert((Record[i] == 3 || Record[i] == 4) &&
830 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +0000831 bool HasValue = (Record[i++] == 4);
832 SmallString<64> KindStr;
833 SmallString<64> ValStr;
834
835 while (Record[i] != 0 && i != e)
836 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000837 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000838
839 if (HasValue) {
840 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +0000841 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +0000842 while (Record[i] != 0 && i != e)
843 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000844 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000845 }
846
847 B.addAttribute(KindStr.str(), ValStr.str());
848 }
849 }
850
Bill Wendlinge46707e2013-02-11 22:32:29 +0000851 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +0000852 break;
853 }
854 }
855 }
856}
857
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000858std::error_code BitcodeReader::ParseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000859 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000860 return Error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +0000861
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000862 return ParseTypeTableBody();
863}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000864
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000865std::error_code BitcodeReader::ParseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +0000866 if (!TypeList.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000867 return Error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +0000868
869 SmallVector<uint64_t, 64> Record;
870 unsigned NumRecords = 0;
871
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000872 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +0000873
Chris Lattner1314b992007-04-22 06:23:29 +0000874 // Read all the records for this type table.
875 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000876 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000877
Chris Lattner27d38752013-01-20 02:13:19 +0000878 switch (Entry.Kind) {
879 case BitstreamEntry::SubBlock: // Handled for us already.
880 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000881 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +0000882 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +0000883 if (NumRecords != TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000884 return Error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000885 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000886 case BitstreamEntry::Record:
887 // The interesting case.
888 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000890
Chris Lattner1314b992007-04-22 06:23:29 +0000891 // Read a record.
892 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +0000893 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +0000894 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +0000895 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000896 return Error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +0000897 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
898 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
899 // type list. This allows us to reserve space.
900 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000901 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000902 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000903 continue;
Chris Lattner1314b992007-04-22 06:23:29 +0000904 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +0000905 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000906 break;
Dan Gohman518cda42011-12-17 00:04:22 +0000907 case bitc::TYPE_CODE_HALF: // HALF
908 ResultTy = Type::getHalfTy(Context);
909 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000910 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +0000911 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000912 break;
913 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +0000914 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000915 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000916 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +0000917 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000918 break;
919 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000920 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000921 break;
922 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000923 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000924 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000925 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +0000926 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000927 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000928 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +0000929 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000930 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +0000931 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
932 ResultTy = Type::getX86_MMXTy(Context);
933 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000934 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
935 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000936 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000937
Owen Anderson55f1c092009-08-13 21:58:54 +0000938 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000939 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000940 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000941 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +0000942 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000943 return Error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000944 unsigned AddressSpace = 0;
945 if (Record.size() == 2)
946 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000947 ResultTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000948 if (!ResultTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000949 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000950 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +0000951 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000952 }
Nuno Lopes561dae02012-05-23 15:19:39 +0000953 case bitc::TYPE_CODE_FUNCTION_OLD: {
954 // FIXME: attrid is dead, remove it in LLVM 4.0
955 // FUNCTION: [vararg, attrid, retty, paramty x N]
956 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000957 return Error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +0000958 SmallVector<Type*, 8> ArgTys;
959 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
960 if (Type *T = getTypeByID(Record[i]))
961 ArgTys.push_back(T);
962 else
963 break;
964 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000965
Nuno Lopes561dae02012-05-23 15:19:39 +0000966 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000967 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000968 return Error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +0000969
970 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
971 break;
972 }
Chad Rosier95898722011-11-03 00:14:01 +0000973 case bitc::TYPE_CODE_FUNCTION: {
974 // FUNCTION: [vararg, retty, paramty x N]
975 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000976 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +0000977 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +0000978 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
979 if (Type *T = getTypeByID(Record[i]))
980 ArgTys.push_back(T);
981 else
982 break;
983 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000984
Chad Rosier95898722011-11-03 00:14:01 +0000985 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000986 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000987 return Error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +0000988
989 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
990 break;
991 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000992 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +0000993 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000994 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +0000995 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000996 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
997 if (Type *T = getTypeByID(Record[i]))
998 EltTys.push_back(T);
999 else
1000 break;
1001 }
1002 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001003 return Error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001004 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001005 break;
1006 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001007 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1008 if (ConvertToString(Record, 0, TypeName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001009 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001010 continue;
1011
1012 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1013 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001014 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001015
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001016 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001017 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001018
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001019 // Check to see if this was forward referenced, if so fill in the temp.
1020 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1021 if (Res) {
1022 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001023 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001024 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001025 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001026 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001027
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001028 SmallVector<Type*, 8> EltTys;
1029 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1030 if (Type *T = getTypeByID(Record[i]))
1031 EltTys.push_back(T);
1032 else
1033 break;
1034 }
1035 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001036 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001037 Res->setBody(EltTys, Record[0]);
1038 ResultTy = Res;
1039 break;
1040 }
1041 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1042 if (Record.size() != 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001043 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001044
1045 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001046 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001047
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001048 // Check to see if this was forward referenced, if so fill in the temp.
1049 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1050 if (Res) {
1051 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001052 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001053 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001054 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001055 TypeName.clear();
1056 ResultTy = Res;
1057 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001058 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001059 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1060 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001061 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001062 if ((ResultTy = getTypeByID(Record[1])))
1063 ResultTy = ArrayType::get(ResultTy, Record[0]);
1064 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001065 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001066 break;
1067 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1068 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001069 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001070 if ((ResultTy = getTypeByID(Record[1])))
1071 ResultTy = VectorType::get(ResultTy, Record[0]);
1072 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001073 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001074 break;
1075 }
1076
1077 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001078 return Error("Invalid TYPE table");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001079 assert(ResultTy && "Didn't read a type?");
Craig Topper2617dcc2014-04-15 06:32:26 +00001080 assert(!TypeList[NumRecords] && "Already read type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001081 TypeList[NumRecords++] = ResultTy;
1082 }
1083}
1084
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001085std::error_code BitcodeReader::ParseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001086 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001087 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001088
1089 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001090
Chris Lattnerccaa4482007-04-23 21:26:05 +00001091 // Read all the records for this value table.
1092 SmallString<128> ValueName;
1093 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001094 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001095
Chris Lattner27d38752013-01-20 02:13:19 +00001096 switch (Entry.Kind) {
1097 case BitstreamEntry::SubBlock: // Handled for us already.
1098 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001099 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001100 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001101 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001102 case BitstreamEntry::Record:
1103 // The interesting case.
1104 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001105 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001106
Chris Lattnerccaa4482007-04-23 21:26:05 +00001107 // Read a record.
1108 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001109 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001110 default: // Default behavior: unknown type.
1111 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001112 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattnerccaa4482007-04-23 21:26:05 +00001113 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001114 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001115 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001116 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001117 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001118 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001119
Daniel Dunbard786b512009-07-26 00:34:27 +00001120 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnerccaa4482007-04-23 21:26:05 +00001121 ValueName.clear();
1122 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001123 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001124 case bitc::VST_CODE_BBENTRY: {
Chris Lattner6be58c62007-05-03 22:18:21 +00001125 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001126 return Error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001127 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001128 if (!BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001129 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001130
Daniel Dunbard786b512009-07-26 00:34:27 +00001131 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001132 ValueName.clear();
1133 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001134 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001135 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001136 }
1137}
1138
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001139std::error_code BitcodeReader::ParseMetadata() {
Devang Patel89923232010-01-11 18:52:33 +00001140 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001141
1142 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001143 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001144
Devang Patel7428d8a2009-07-22 17:43:22 +00001145 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001146
Devang Patel7428d8a2009-07-22 17:43:22 +00001147 // Read all the records.
1148 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001149 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001150
Chris Lattner27d38752013-01-20 02:13:19 +00001151 switch (Entry.Kind) {
1152 case BitstreamEntry::SubBlock: // Handled for us already.
1153 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001154 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001155 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001156 MDValueList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001157 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001158 case BitstreamEntry::Record:
1159 // The interesting case.
1160 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001161 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001162
Devang Patel7428d8a2009-07-22 17:43:22 +00001163 // Read a record.
1164 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001165 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001166 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001167 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001168 default: // Default behavior: ignore.
1169 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001170 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001171 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001172 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001173 Record.clear();
1174 Code = Stream.ReadCode();
1175
Chris Lattnerb8778552011-06-17 17:50:30 +00001176 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner27d38752013-01-20 02:13:19 +00001177 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattnerb8778552011-06-17 17:50:30 +00001178 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patel27c87ff2009-07-29 22:34:41 +00001179
1180 // Read named metadata elements.
1181 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001182 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001183 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001184 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001185 if (!MD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001186 return Error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001187 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001188 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001189 break;
1190 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001191 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001192 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001193 // This is a LocalAsMetadata record, the only type of function-local
1194 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001195 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001196 return Error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001197
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001198 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1199 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001200 auto dropRecord = [&] {
1201 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1202 };
1203 if (Record.size() != 2) {
1204 dropRecord();
1205 break;
1206 }
1207
1208 Type *Ty = getTypeByID(Record[0]);
1209 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1210 dropRecord();
1211 break;
1212 }
1213
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001214 MDValueList.AssignValue(
1215 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1216 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001217 break;
1218 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001219 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001220 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001221 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001222 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001223
Devang Patele059ba6e2009-07-23 01:07:34 +00001224 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001225 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001226 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001227 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001228 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001229 return Error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00001230 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001231 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001232 else if (!Ty->isVoidTy()) {
1233 auto *MD =
1234 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1235 assert(isa<ConstantAsMetadata>(MD) &&
1236 "Expected non-function-local metadata");
1237 Elts.push_back(MD);
1238 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00001239 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001240 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001241 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001242 break;
1243 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001244 case bitc::METADATA_VALUE: {
1245 if (Record.size() != 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001246 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001247
1248 Type *Ty = getTypeByID(Record[0]);
1249 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001250 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001251
1252 MDValueList.AssignValue(
1253 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1254 NextMDValueNo++);
1255 break;
1256 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001257 case bitc::METADATA_DISTINCT_NODE:
1258 IsDistinct = true;
1259 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001260 case bitc::METADATA_NODE: {
1261 SmallVector<Metadata *, 8> Elts;
1262 Elts.reserve(Record.size());
1263 for (unsigned ID : Record)
1264 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001265 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1266 : MDNode::get(Context, Elts),
1267 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001268 break;
1269 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001270 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00001271 std::string String(Record.begin(), Record.end());
1272 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001273 Metadata *MD = MDString::get(Context, String);
1274 MDValueList.AssignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00001275 break;
1276 }
Devang Patelaf206b82009-09-18 19:26:43 +00001277 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001278 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001279 return Error("Invalid record");
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001280
Devang Patelb1a44772009-09-28 21:14:55 +00001281 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001282 SmallString<8> Name(Record.begin()+1, Record.end());
1283
Chris Lattnera0566972009-12-29 09:01:33 +00001284 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00001285 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001286 return Error("Conflicting METADATA_KIND records");
Devang Patelaf206b82009-09-18 19:26:43 +00001287 break;
1288 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001289 }
1290 }
1291}
1292
Jan Wen Voungafaced02012-10-11 20:20:40 +00001293/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner08feb1e2007-04-24 04:04:35 +00001294/// the LSB for dense VBR encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001295uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001296 if ((V & 1) == 0)
1297 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001298 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001299 return -(V >> 1);
1300 // There is no such thing as -0 with integers. "-0" really means MININT.
1301 return 1ULL << 63;
1302}
1303
Chris Lattner44c17072007-04-26 02:46:40 +00001304/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1305/// values and aliases that we can.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001306std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00001307 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1308 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001309 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001310 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001311
Chris Lattner44c17072007-04-26 02:46:40 +00001312 GlobalInitWorklist.swap(GlobalInits);
1313 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001314 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001315 FunctionPrologueWorklist.swap(FunctionPrologues);
Chris Lattner44c17072007-04-26 02:46:40 +00001316
1317 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00001318 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001319 if (ValID >= ValueList.size()) {
1320 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00001321 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001322 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001323 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00001324 GlobalInitWorklist.back().first->setInitializer(C);
1325 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001326 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00001327 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001328 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001329 }
1330
1331 while (!AliasInitWorklist.empty()) {
1332 unsigned ValID = AliasInitWorklist.back().second;
1333 if (ValID >= ValueList.size()) {
1334 AliasInits.push_back(AliasInitWorklist.back());
1335 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001336 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Rafael Espindola64c1e182014-06-03 02:41:57 +00001337 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00001338 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001339 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00001340 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001341 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001342 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001343
1344 while (!FunctionPrefixWorklist.empty()) {
1345 unsigned ValID = FunctionPrefixWorklist.back().second;
1346 if (ValID >= ValueList.size()) {
1347 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1348 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001349 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001350 FunctionPrefixWorklist.back().first->setPrefixData(C);
1351 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001352 return Error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001353 }
1354 FunctionPrefixWorklist.pop_back();
1355 }
1356
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001357 while (!FunctionPrologueWorklist.empty()) {
1358 unsigned ValID = FunctionPrologueWorklist.back().second;
1359 if (ValID >= ValueList.size()) {
1360 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1361 } else {
1362 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1363 FunctionPrologueWorklist.back().first->setPrologueData(C);
1364 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001365 return Error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001366 }
1367 FunctionPrologueWorklist.pop_back();
1368 }
1369
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001370 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00001371}
1372
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001373static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1374 SmallVector<uint64_t, 8> Words(Vals.size());
1375 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00001376 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001377
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001378 return APInt(TypeBits, Words);
1379}
1380
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001381std::error_code BitcodeReader::ParseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001382 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001383 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001384
1385 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001386
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001387 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00001388 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00001389 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001390 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001391 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001392
Chris Lattner27d38752013-01-20 02:13:19 +00001393 switch (Entry.Kind) {
1394 case BitstreamEntry::SubBlock: // Handled for us already.
1395 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001396 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001397 case BitstreamEntry::EndBlock:
1398 if (NextCstNo != ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001399 return Error("Invalid ronstant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00001400
Chris Lattner27d38752013-01-20 02:13:19 +00001401 // Once all the constants have been read, go through and resolve forward
1402 // references.
1403 ValueList.ResolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001404 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001405 case BitstreamEntry::Record:
1406 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00001407 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001408 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001409
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001410 // Read a record.
1411 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001412 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001413 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00001414 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001415 default: // Default behavior: unknown constant
1416 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00001417 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001418 break;
1419 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1420 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001421 return Error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00001422 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001423 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001424 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00001425 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001426 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00001427 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001428 break;
1429 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001430 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001431 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00001432 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00001433 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001434 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001435 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001436 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001437
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001438 APInt VInt = ReadWideAPInt(Record,
1439 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001440 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001441
Chris Lattner08feb1e2007-04-24 04:04:35 +00001442 break;
1443 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00001444 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00001445 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001446 return Error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00001447 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00001448 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1449 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00001450 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00001451 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1452 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001453 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00001454 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1455 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001456 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00001457 // Bits are not stored the same way as a normal i80 APInt, compensate.
1458 uint64_t Rearrange[2];
1459 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1460 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00001461 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1462 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001463 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001464 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1465 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001466 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001467 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1468 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001469 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001470 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001471 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00001472 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001473
Chris Lattnere14cb882007-05-04 19:11:41 +00001474 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1475 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001476 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001477
Chris Lattnere14cb882007-05-04 19:11:41 +00001478 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001479 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001480
Chris Lattner229907c2011-07-18 04:54:35 +00001481 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00001482 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001483 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00001484 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00001485 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001486 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1487 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001488 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001489 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00001490 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001491 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1492 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001493 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001494 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00001495 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00001496 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001497 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00001498 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001499 break;
1500 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001501 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00001502 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1503 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001504 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001505
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001506 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001507 V = ConstantDataArray::getString(Context, Elts,
1508 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00001509 break;
1510 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00001511 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1512 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001513 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001514
Chris Lattner372dd1e2012-01-30 00:51:16 +00001515 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1516 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001517
Chris Lattner372dd1e2012-01-30 00:51:16 +00001518 if (EltTy->isIntegerTy(8)) {
1519 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1520 if (isa<VectorType>(CurTy))
1521 V = ConstantDataVector::get(Context, Elts);
1522 else
1523 V = ConstantDataArray::get(Context, Elts);
1524 } else if (EltTy->isIntegerTy(16)) {
1525 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1526 if (isa<VectorType>(CurTy))
1527 V = ConstantDataVector::get(Context, Elts);
1528 else
1529 V = ConstantDataArray::get(Context, Elts);
1530 } else if (EltTy->isIntegerTy(32)) {
1531 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1532 if (isa<VectorType>(CurTy))
1533 V = ConstantDataVector::get(Context, Elts);
1534 else
1535 V = ConstantDataArray::get(Context, Elts);
1536 } else if (EltTy->isIntegerTy(64)) {
1537 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1538 if (isa<VectorType>(CurTy))
1539 V = ConstantDataVector::get(Context, Elts);
1540 else
1541 V = ConstantDataArray::get(Context, Elts);
1542 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001543 SmallVector<float, 16> Elts(Size);
1544 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001545 if (isa<VectorType>(CurTy))
1546 V = ConstantDataVector::get(Context, Elts);
1547 else
1548 V = ConstantDataArray::get(Context, Elts);
1549 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001550 SmallVector<double, 16> Elts(Size);
1551 std::transform(Record.begin(), Record.end(), Elts.begin(),
1552 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001553 if (isa<VectorType>(CurTy))
1554 V = ConstantDataVector::get(Context, Elts);
1555 else
1556 V = ConstantDataArray::get(Context, Elts);
1557 } else {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001558 return Error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00001559 }
1560 break;
1561 }
1562
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001563 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001564 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001565 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001566 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001567 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001568 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00001569 } else {
1570 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1571 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00001572 unsigned Flags = 0;
1573 if (Record.size() >= 4) {
1574 if (Opc == Instruction::Add ||
1575 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001576 Opc == Instruction::Mul ||
1577 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00001578 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1579 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1580 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1581 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00001582 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001583 Opc == Instruction::UDiv ||
1584 Opc == Instruction::LShr ||
1585 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00001586 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00001587 Flags |= SDivOperator::IsExact;
1588 }
1589 }
1590 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00001591 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001592 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001593 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001594 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001595 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001596 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001597 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00001598 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001599 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00001600 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00001601 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001602 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001603 return Error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00001604 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001605 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1606 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001607 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001608 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001609 }
Dan Gohman1639c392009-07-27 21:53:46 +00001610 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001611 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001612 if (Record.size() & 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001613 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001614 SmallVector<Constant*, 16> Elts;
Chris Lattnere14cb882007-05-04 19:11:41 +00001615 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001616 Type *ElTy = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001617 if (!ElTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001618 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001619 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1620 }
Jay Foaded8db7d2011-07-21 14:31:17 +00001621 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad2f5fc8c2011-07-21 15:15:37 +00001622 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1623 BitCode ==
1624 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00001625 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001626 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00001627 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001628 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001629 return Error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00001630
1631 Type *SelectorTy = Type::getInt1Ty(Context);
1632
1633 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1634 // vector. Otherwise, it must be a single bit.
1635 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1636 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1637 VTy->getNumElements());
1638
1639 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1640 SelectorTy),
1641 ValueList.getConstantFwdRef(Record[1],CurTy),
1642 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001643 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00001644 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001645 case bitc::CST_CODE_CE_EXTRACTELT
1646 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001647 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001648 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00001649 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001650 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001651 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001652 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001653 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001654 Constant *Op1 = nullptr;
1655 if (Record.size() == 4) {
1656 Type *IdxTy = getTypeByID(Record[2]);
1657 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001658 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001659 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1660 } else // TODO: Remove with llvm 4.0
1661 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1662 if (!Op1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001663 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00001664 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001665 break;
1666 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001667 case bitc::CST_CODE_CE_INSERTELT
1668 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001669 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00001670 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001671 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001672 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1673 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1674 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001675 Constant *Op2 = nullptr;
1676 if (Record.size() == 4) {
1677 Type *IdxTy = getTypeByID(Record[2]);
1678 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001679 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001680 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1681 } else // TODO: Remove with llvm 4.0
1682 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1683 if (!Op2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001684 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00001685 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001686 break;
1687 }
1688 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001689 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00001690 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001691 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001692 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1693 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001694 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00001695 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001696 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00001697 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001698 break;
1699 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00001700 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001701 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1702 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00001703 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001704 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001705 return Error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00001706 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1707 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001708 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00001709 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00001710 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00001711 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00001712 break;
1713 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001714 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001715 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001716 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00001717 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001718 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001719 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001720 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1721 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1722
Duncan Sands9dff9be2010-02-15 16:12:20 +00001723 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00001724 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00001725 else
Owen Anderson487375e2009-07-29 18:55:55 +00001726 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001727 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00001728 }
Chad Rosierd8c76102012-09-05 19:00:49 +00001729 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00001730 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001731 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001732 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001733 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001734 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00001735 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00001736 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001737 unsigned AsmStrSize = Record[1];
1738 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001739 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001740 unsigned ConstStrSize = Record[2+AsmStrSize];
1741 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001742 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001743
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001744 for (unsigned i = 0; i != AsmStrSize; ++i)
1745 AsmStr += (char)Record[2+i];
1746 for (unsigned i = 0; i != ConstStrSize; ++i)
1747 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00001748 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001749 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00001750 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001751 break;
1752 }
Chad Rosierd8c76102012-09-05 19:00:49 +00001753 // This version adds support for the asm dialect keywords (e.g.,
1754 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001755 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001756 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001757 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001758 std::string AsmStr, ConstrStr;
1759 bool HasSideEffects = Record[0] & 1;
1760 bool IsAlignStack = (Record[0] >> 1) & 1;
1761 unsigned AsmDialect = Record[0] >> 2;
1762 unsigned AsmStrSize = Record[1];
1763 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001764 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001765 unsigned ConstStrSize = Record[2+AsmStrSize];
1766 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001767 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001768
1769 for (unsigned i = 0; i != AsmStrSize; ++i)
1770 AsmStr += (char)Record[2+i];
1771 for (unsigned i = 0; i != ConstStrSize; ++i)
1772 ConstrStr += (char)Record[3+AsmStrSize+i];
1773 PointerType *PTy = cast<PointerType>(CurTy);
1774 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1775 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00001776 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001777 break;
1778 }
Chris Lattner5956dc82009-10-28 05:53:48 +00001779 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00001780 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001781 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00001782 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001783 if (!FnTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001784 return Error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00001785 Function *Fn =
1786 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00001787 if (!Fn)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001788 return Error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001789
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00001790 // Don't let Fn get dematerialized.
1791 BlockAddressesTaken.insert(Fn);
1792
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001793 // If the function is already parsed we can insert the block address right
1794 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001795 BasicBlock *BB;
1796 unsigned BBID = Record[2];
1797 if (!BBID)
1798 // Invalid reference to entry block.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001799 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001800 if (!Fn->empty()) {
1801 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001802 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001803 if (BBI == BBE)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001804 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001805 ++BBI;
1806 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001807 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001808 } else {
1809 // Otherwise insert a placeholder and remember it so it can be inserted
1810 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00001811 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1812 if (FwdBBs.empty())
1813 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00001814 if (FwdBBs.size() < BBID + 1)
1815 FwdBBs.resize(BBID + 1);
1816 if (!FwdBBs[BBID])
1817 FwdBBs[BBID] = BasicBlock::Create(Context);
1818 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001819 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001820 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00001821 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001822 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001823 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001824
Chris Lattner83930552007-05-01 07:01:57 +00001825 ValueList.AssignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00001826 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001827 }
1828}
Chris Lattner1314b992007-04-22 06:23:29 +00001829
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001830std::error_code BitcodeReader::ParseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00001831 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001832 return Error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00001833
Chad Rosierca2567b2011-12-07 21:44:12 +00001834 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001835 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00001836 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001837 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001838
Chris Lattner27d38752013-01-20 02:13:19 +00001839 switch (Entry.Kind) {
1840 case BitstreamEntry::SubBlock: // Handled for us already.
1841 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001842 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001843 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001844 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001845 case BitstreamEntry::Record:
1846 // The interesting case.
1847 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00001848 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001849
Chad Rosierca2567b2011-12-07 21:44:12 +00001850 // Read a use list record.
1851 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001852 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00001853 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00001854 default: // Default behavior: unknown type.
1855 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001856 case bitc::USELIST_CODE_BB:
1857 IsBB = true;
1858 // fallthrough
1859 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00001860 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001861 if (RecordLength < 3)
1862 // Records should have at least an ID and two indexes.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001863 return Error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001864 unsigned ID = Record.back();
1865 Record.pop_back();
1866
1867 Value *V;
1868 if (IsBB) {
1869 assert(ID < FunctionBBs.size() && "Basic block not found");
1870 V = FunctionBBs[ID];
1871 } else
1872 V = ValueList[ID];
1873 unsigned NumUses = 0;
1874 SmallDenseMap<const Use *, unsigned, 16> Order;
1875 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00001876 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001877 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00001878 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001879 }
1880 if (Order.size() != Record.size() || NumUses > Record.size())
1881 // Mismatches can happen if the functions are being materialized lazily
1882 // (out-of-order), or a value has been upgraded.
1883 break;
1884
1885 V->sortUseList([&](const Use &L, const Use &R) {
1886 return Order.lookup(&L) < Order.lookup(&R);
1887 });
Chad Rosierca2567b2011-12-07 21:44:12 +00001888 break;
1889 }
1890 }
1891 }
1892}
1893
Chris Lattner85b7b402007-05-01 05:52:21 +00001894/// RememberAndSkipFunctionBody - When we see the block for a function body,
1895/// remember where it is and then skip it. This lets us lazily deserialize the
1896/// functions.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001897std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001898 // Get the function we are talking about.
1899 if (FunctionsWithBodies.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001900 return Error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001901
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001902 Function *Fn = FunctionsWithBodies.back();
1903 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001904
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001905 // Save the current stream state.
1906 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001907 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001908
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001909 // Skip over the function block for now.
1910 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001911 return Error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001912 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001913}
1914
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001915std::error_code BitcodeReader::GlobalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001916 // Patch the initializers for globals and aliases up.
1917 ResolveGlobalAndAliasInits();
1918 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001919 return Error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001920
1921 // Look for intrinsic functions which need to be upgraded at some point
1922 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1923 FI != FE; ++FI) {
1924 Function *NewFn;
1925 if (UpgradeIntrinsicFunction(FI, NewFn))
1926 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1927 }
1928
1929 // Look for global variables which need to be renamed.
1930 for (Module::global_iterator
1931 GI = TheModule->global_begin(), GE = TheModule->global_end();
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001932 GI != GE;) {
1933 GlobalVariable *GV = GI++;
1934 UpgradeGlobalVariable(GV);
1935 }
1936
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001937 // Force deallocation of memory for these vectors to favor the client that
1938 // want lazy deserialization.
1939 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1940 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001941 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001942}
1943
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001944std::error_code BitcodeReader::ParseModule(bool Resume) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001945 if (Resume)
1946 Stream.JumpToBit(NextUnreadBit);
1947 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001948 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00001949
Chris Lattner1314b992007-04-22 06:23:29 +00001950 SmallVector<uint64_t, 64> Record;
1951 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00001952 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00001953
1954 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00001955 while (1) {
1956 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00001957
Chris Lattner27d38752013-01-20 02:13:19 +00001958 switch (Entry.Kind) {
1959 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001960 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001961 case BitstreamEntry::EndBlock:
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001962 return GlobalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00001963
Chris Lattner27d38752013-01-20 02:13:19 +00001964 case BitstreamEntry::SubBlock:
1965 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00001966 default: // Skip unknown content.
1967 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001968 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00001969 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00001970 case bitc::BLOCKINFO_BLOCK_ID:
1971 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001972 return Error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00001973 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001974 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001975 if (std::error_code EC = ParseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001976 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001977 break;
Bill Wendlingba629332013-02-10 23:24:25 +00001978 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001979 if (std::error_code EC = ParseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001980 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00001981 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001982 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001983 if (std::error_code EC = ParseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001984 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00001985 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001986 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001987 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001988 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001989 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001990 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001991 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001992 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001993 return EC;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001994 if (std::error_code EC = ResolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001995 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001996 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001997 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001998 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001999 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00002000 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002001 case bitc::FUNCTION_BLOCK_ID:
2002 // If this is the first function body we've seen, reverse the
2003 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002004 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002005 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002006 if (std::error_code EC = GlobalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002007 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002008 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002009 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002010
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002011 if (std::error_code EC = RememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002012 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002013 // For streaming bitcode, suspend parsing when we reach the function
2014 // bodies. Subsequent materialization calls will resume it when
2015 // necessary. For streaming, the function bodies must be at the end of
2016 // the bitcode. If the bitcode file is old, the symbol table will be
2017 // at the end instead and will not have been seen yet. In this case,
2018 // just finish the parse now.
2019 if (LazyStreamer && SeenValueSymbolTable) {
2020 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002021 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002022 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002023 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002024 case bitc::USELIST_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002025 if (std::error_code EC = ParseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002026 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00002027 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002028 }
2029 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002030
Chris Lattner27d38752013-01-20 02:13:19 +00002031 case BitstreamEntry::Record:
2032 // The interesting case.
2033 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002034 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002035
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002036
Chris Lattner1314b992007-04-22 06:23:29 +00002037 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002038 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00002039 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002040 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00002041 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002042 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002043 // Only version #0 and #1 are supported so far.
2044 unsigned module_version = Record[0];
2045 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002046 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002047 return Error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002048 case 0:
2049 UseRelativeIDs = false;
2050 break;
2051 case 1:
2052 UseRelativeIDs = true;
2053 break;
2054 }
Chris Lattner1314b992007-04-22 06:23:29 +00002055 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002056 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002057 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002058 std::string S;
2059 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002060 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002061 TheModule->setTargetTriple(S);
2062 break;
2063 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002064 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002065 std::string S;
2066 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002067 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002068 TheModule->setDataLayout(S);
2069 break;
2070 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002071 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002072 std::string S;
2073 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002074 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002075 TheModule->setModuleInlineAsm(S);
2076 break;
2077 }
Bill Wendling706d3d62012-11-28 08:41:48 +00002078 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2079 // FIXME: Remove in 4.0.
2080 std::string S;
2081 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002082 return Error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00002083 // Ignore value.
2084 break;
2085 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002086 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002087 std::string S;
2088 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002089 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002090 SectionTable.push_back(S);
2091 break;
2092 }
Gordon Henriksend930f912008-08-17 18:44:35 +00002093 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00002094 std::string S;
2095 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002096 return Error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00002097 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00002098 break;
2099 }
David Majnemerdad0a642014-06-27 18:19:56 +00002100 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2101 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002102 return Error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00002103 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2104 unsigned ComdatNameSize = Record[1];
2105 std::string ComdatName;
2106 ComdatName.reserve(ComdatNameSize);
2107 for (unsigned i = 0; i != ComdatNameSize; ++i)
2108 ComdatName += (char)Record[2 + i];
2109 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2110 C->setSelectionKind(SK);
2111 ComdatList.push_back(C);
2112 break;
2113 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002114 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00002115 // linkage, alignment, section, visibility, threadlocal,
Nico Rieck7157bb72014-01-14 15:22:47 +00002116 // unnamed_addr, dllstorageclass]
Chris Lattner1314b992007-04-22 06:23:29 +00002117 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00002118 if (Record.size() < 6)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002119 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002120 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002121 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002122 return Error("Invalid record");
Duncan Sands19d0b472010-02-16 11:11:14 +00002123 if (!Ty->isPointerTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002124 return Error("Invalid type for value");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002125 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattner1314b992007-04-22 06:23:29 +00002126 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002127
Chris Lattner1314b992007-04-22 06:23:29 +00002128 bool isConstant = Record[1];
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00002129 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]);
Chris Lattner1314b992007-04-22 06:23:29 +00002130 unsigned Alignment = (1 << Record[4]) >> 1;
2131 std::string Section;
2132 if (Record[5]) {
2133 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002134 return Error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00002135 Section = SectionTable[Record[5]-1];
2136 }
Chris Lattner4b00d922007-04-23 16:04:05 +00002137 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002138 // Local linkage must have default visibility.
2139 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2140 // FIXME: Change to an error if non-default in 4.0.
Chris Lattner53862f72007-05-06 19:27:46 +00002141 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002142
2143 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00002144 if (Record.size() > 7)
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002145 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00002146
Rafael Espindola45e6c192011-01-08 16:42:36 +00002147 bool UnnamedAddr = false;
2148 if (Record.size() > 8)
2149 UnnamedAddr = Record[8];
2150
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002151 bool ExternallyInitialized = false;
2152 if (Record.size() > 9)
2153 ExternallyInitialized = Record[9];
2154
Chris Lattner1314b992007-04-22 06:23:29 +00002155 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00002156 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002157 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00002158 NewGV->setAlignment(Alignment);
2159 if (!Section.empty())
2160 NewGV->setSection(Section);
2161 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00002162 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002163
Nico Rieck7157bb72014-01-14 15:22:47 +00002164 if (Record.size() > 10)
2165 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2166 else
2167 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2168
Chris Lattnerccaa4482007-04-23 21:26:05 +00002169 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002170
Chris Lattner47d131b2007-04-24 00:18:21 +00002171 // Remember which value to use for the global initializer.
2172 if (unsigned InitID = Record[2])
2173 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00002174
2175 if (Record.size() > 11)
2176 if (unsigned ComdatID = Record[11]) {
2177 assert(ComdatID <= ComdatList.size());
2178 NewGV->setComdat(ComdatList[ComdatID - 1]);
2179 }
Chris Lattner1314b992007-04-22 06:23:29 +00002180 break;
2181 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002182 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00002183 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002184 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00002185 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002186 if (Record.size() < 8)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002187 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002188 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002189 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002190 return Error("Invalid record");
Duncan Sands19d0b472010-02-16 11:11:14 +00002191 if (!Ty->isPointerTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002192 return Error("Invalid type for value");
Chris Lattner229907c2011-07-18 04:54:35 +00002193 FunctionType *FTy =
Chris Lattner1314b992007-04-22 06:23:29 +00002194 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2195 if (!FTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002196 return Error("Invalid type for value");
Chris Lattner1314b992007-04-22 06:23:29 +00002197
Gabor Greife9ecc682008-04-06 20:25:17 +00002198 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2199 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00002200
Sandeep Patel68c5f472009-09-02 08:44:58 +00002201 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002202 bool isProto = Record[2];
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00002203 Func->setLinkage(getDecodedLinkage(Record[3]));
Devang Patel4c758ea2008-09-25 21:00:45 +00002204 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002205
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002206 Func->setAlignment((1 << Record[5]) >> 1);
2207 if (Record[6]) {
2208 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002209 return Error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002210 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00002211 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002212 // Local linkage must have default visibility.
2213 if (!Func->hasLocalLinkage())
2214 // FIXME: Change to an error if non-default in 4.0.
2215 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00002216 if (Record.size() > 8 && Record[8]) {
Gordon Henriksend930f912008-08-17 18:44:35 +00002217 if (Record[8]-1 > GCTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002218 return Error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00002219 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00002220 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00002221 bool UnnamedAddr = false;
2222 if (Record.size() > 9)
2223 UnnamedAddr = Record[9];
2224 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002225 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002226 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00002227
2228 if (Record.size() > 11)
2229 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2230 else
2231 UpgradeDLLImportExportLinkage(Func, Record[3]);
2232
David Majnemerdad0a642014-06-27 18:19:56 +00002233 if (Record.size() > 12)
2234 if (unsigned ComdatID = Record[12]) {
2235 assert(ComdatID <= ComdatList.size());
2236 Func->setComdat(ComdatList[ComdatID - 1]);
2237 }
2238
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002239 if (Record.size() > 13 && Record[13] != 0)
2240 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2241
Chris Lattnerccaa4482007-04-23 21:26:05 +00002242 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002243
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002244 // If this is a function with a body, remember the prototype we are
2245 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002246 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00002247 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002248 FunctionsWithBodies.push_back(Func);
Rafael Espindola1b47a282014-10-23 15:20:05 +00002249 if (LazyStreamer)
2250 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002251 }
Chris Lattner1314b992007-04-22 06:23:29 +00002252 break;
2253 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002254 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00002255 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00002256 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00002257 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002258 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002259 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002260 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002261 return Error("Invalid record");
Rafael Espindolaa8004452014-05-16 14:22:33 +00002262 auto *PTy = dyn_cast<PointerType>(Ty);
2263 if (!PTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002264 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002265
Rafael Espindolaa8004452014-05-16 14:22:33 +00002266 auto *NewGA =
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00002267 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00002268 getDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002269 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002270 // Local linkage must have default visibility.
2271 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2272 // FIXME: Change to an error if non-default in 4.0.
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002273 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00002274 if (Record.size() > 4)
2275 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2276 else
2277 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00002278 if (Record.size() > 5)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00002279 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00002280 if (Record.size() > 6)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00002281 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00002282 ValueList.push_back(NewGA);
2283 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2284 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002285 }
Chris Lattner831d4202007-04-26 03:27:58 +00002286 /// MODULE_CODE_PURGEVALS: [numvals]
2287 case bitc::MODULE_CODE_PURGEVALS:
2288 // Trim down the value list to the specified size.
2289 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002290 return Error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00002291 ValueList.shrinkTo(Record[0]);
2292 break;
2293 }
Chris Lattner1314b992007-04-22 06:23:29 +00002294 Record.clear();
2295 }
Chris Lattner1314b992007-04-22 06:23:29 +00002296}
2297
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002298std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002299 TheModule = nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002300
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002301 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002302 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002303
Chris Lattner1314b992007-04-22 06:23:29 +00002304 // Sniff for the signature.
2305 if (Stream.Read(8) != 'B' ||
2306 Stream.Read(8) != 'C' ||
2307 Stream.Read(4) != 0x0 ||
2308 Stream.Read(4) != 0xC ||
2309 Stream.Read(4) != 0xE ||
2310 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002311 return Error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312
Chris Lattner1314b992007-04-22 06:23:29 +00002313 // We expect a number of well-defined blocks, though we don't necessarily
2314 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002315 while (1) {
2316 if (Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002317 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002318
Chris Lattner27d38752013-01-20 02:13:19 +00002319 BitstreamEntry Entry =
2320 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00002321
Chris Lattner27d38752013-01-20 02:13:19 +00002322 switch (Entry.Kind) {
2323 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002324 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002325 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002326 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002327
Chris Lattner27d38752013-01-20 02:13:19 +00002328 case BitstreamEntry::SubBlock:
2329 switch (Entry.ID) {
2330 case bitc::BLOCKINFO_BLOCK_ID:
2331 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002332 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002333 break;
2334 case bitc::MODULE_BLOCK_ID:
2335 // Reject multiple MODULE_BLOCK's in a single bitstream.
2336 if (TheModule)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002337 return Error("Invalid multiple blocks");
Chris Lattner27d38752013-01-20 02:13:19 +00002338 TheModule = M;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002339 if (std::error_code EC = ParseModule(false))
Rafael Espindola48da4f42013-11-04 16:16:24 +00002340 return EC;
2341 if (LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002342 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002343 break;
2344 default:
2345 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002346 return Error("Invalid record");
Chris Lattner27d38752013-01-20 02:13:19 +00002347 break;
2348 }
2349 continue;
2350 case BitstreamEntry::Record:
2351 // There should be no records in the top-level of blocks.
Joe Abbey97b7a172013-02-06 22:14:06 +00002352
Chris Lattner27d38752013-01-20 02:13:19 +00002353 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosiera15e3aa2011-08-09 22:23:40 +00002354 // to the end of them. If this file size is a multiple of 4 but not 8, we
2355 // have to read and ignore these final 4 bytes :-(
Chris Lattner27d38752013-01-20 02:13:19 +00002356 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002357 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling318f03f2012-07-19 00:15:11 +00002358 Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002359 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002360
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002361 return Error("Invalid record");
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002362 }
Chris Lattner1314b992007-04-22 06:23:29 +00002363 }
Chris Lattner1314b992007-04-22 06:23:29 +00002364}
Chris Lattner6694f602007-04-29 07:54:31 +00002365
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002366ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00002367 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002368 return Error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00002369
2370 SmallVector<uint64_t, 64> Record;
2371
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002372 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00002373 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002374 while (1) {
2375 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002376
Chris Lattner27d38752013-01-20 02:13:19 +00002377 switch (Entry.Kind) {
2378 case BitstreamEntry::SubBlock: // Handled for us already.
2379 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002380 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002381 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00002382 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00002383 case BitstreamEntry::Record:
2384 // The interesting case.
2385 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00002386 }
2387
2388 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002389 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00002390 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00002391 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002392 std::string S;
2393 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002394 return Error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002395 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00002396 break;
2397 }
2398 }
2399 Record.clear();
2400 }
Rafael Espindolae6107792014-07-04 20:05:56 +00002401 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00002402}
2403
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002404ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002405 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002406 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00002407
2408 // Sniff for the signature.
2409 if (Stream.Read(8) != 'B' ||
2410 Stream.Read(8) != 'C' ||
2411 Stream.Read(4) != 0x0 ||
2412 Stream.Read(4) != 0xC ||
2413 Stream.Read(4) != 0xE ||
2414 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002415 return Error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00002416
2417 // We expect a number of well-defined blocks, though we don't necessarily
2418 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002419 while (1) {
2420 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002421
Chris Lattner27d38752013-01-20 02:13:19 +00002422 switch (Entry.Kind) {
2423 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002424 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002425 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002426 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002427
Chris Lattner27d38752013-01-20 02:13:19 +00002428 case BitstreamEntry::SubBlock:
2429 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00002430 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00002431
Chris Lattner27d38752013-01-20 02:13:19 +00002432 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00002433 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002434 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002435 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002436
Chris Lattner27d38752013-01-20 02:13:19 +00002437 case BitstreamEntry::Record:
2438 Stream.skipRecord(Entry.ID);
2439 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00002440 }
2441 }
Bill Wendling0198ce02010-10-06 01:22:42 +00002442}
2443
Devang Patelaf206b82009-09-18 19:26:43 +00002444/// ParseMetadataAttachment - Parse metadata attachments.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002445std::error_code BitcodeReader::ParseMetadataAttachment() {
Devang Patelaf206b82009-09-18 19:26:43 +00002446 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002447 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002448
Devang Patelaf206b82009-09-18 19:26:43 +00002449 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00002450 while (1) {
2451 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002452
Chris Lattner27d38752013-01-20 02:13:19 +00002453 switch (Entry.Kind) {
2454 case BitstreamEntry::SubBlock: // Handled for us already.
2455 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002456 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002457 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002458 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002459 case BitstreamEntry::Record:
2460 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00002461 break;
2462 }
Chris Lattner27d38752013-01-20 02:13:19 +00002463
Devang Patelaf206b82009-09-18 19:26:43 +00002464 // Read a metadata attachment record.
2465 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00002466 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00002467 default: // Default behavior: ignore.
2468 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00002469 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00002470 unsigned RecordLength = Record.size();
2471 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002472 return Error("Invalid record");
Devang Patelaf206b82009-09-18 19:26:43 +00002473 Instruction *Inst = InstructionList[Record[0]];
2474 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00002475 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00002476 DenseMap<unsigned, unsigned>::iterator I =
2477 MDKindMap.find(Kind);
2478 if (I == MDKindMap.end())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002479 return Error("Invalid ID");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002480 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2481 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00002482 // Drop the attachment. This used to be legal, but there's no
2483 // upgrade path.
2484 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002485 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00002486 if (I->second == LLVMContext::MD_tbaa)
2487 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00002488 }
2489 break;
2490 }
2491 }
2492 }
Devang Patelaf206b82009-09-18 19:26:43 +00002493}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002494
Chris Lattner85b7b402007-05-01 05:52:21 +00002495/// ParseFunctionBody - Lazily parse the specified function body block.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002496std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002497 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002498 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
Nick Lewyckya72e1af2010-02-25 08:30:17 +00002500 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00002501 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00002502 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002503
Chris Lattner85b7b402007-05-01 05:52:21 +00002504 // Add all the function arguments to the value table.
2505 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2506 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002507
Chris Lattner83930552007-05-01 07:01:57 +00002508 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00002509 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00002510 unsigned CurBBNo = 0;
2511
Chris Lattner07d09ed2010-04-03 02:17:50 +00002512 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002513 auto getLastInstruction = [&]() -> Instruction * {
2514 if (CurBB && !CurBB->empty())
2515 return &CurBB->back();
2516 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2517 !FunctionBBs[CurBBNo - 1]->empty())
2518 return &FunctionBBs[CurBBNo - 1]->back();
2519 return nullptr;
2520 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002521
Chris Lattner85b7b402007-05-01 05:52:21 +00002522 // Read all the records.
2523 SmallVector<uint64_t, 64> Record;
2524 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002525 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002526
Chris Lattner27d38752013-01-20 02:13:19 +00002527 switch (Entry.Kind) {
2528 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002529 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002530 case BitstreamEntry::EndBlock:
2531 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00002532
Chris Lattner27d38752013-01-20 02:13:19 +00002533 case BitstreamEntry::SubBlock:
2534 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00002535 default: // Skip unknown content.
2536 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002537 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00002538 break;
2539 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002540 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002541 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00002542 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00002543 break;
2544 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002545 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002546 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00002547 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002548 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002549 if (std::error_code EC = ParseMetadataAttachment())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002550 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002551 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002552 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002553 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002554 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002555 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002556 case bitc::USELIST_BLOCK_ID:
2557 if (std::error_code EC = ParseUseLists())
2558 return EC;
2559 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002560 }
2561 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002562
Chris Lattner27d38752013-01-20 02:13:19 +00002563 case BitstreamEntry::Record:
2564 // The interesting case.
2565 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002566 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002567
Chris Lattner85b7b402007-05-01 05:52:21 +00002568 // Read a record.
2569 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002570 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002571 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002572 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00002573 default: // Default behavior: reject
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002574 return Error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002575 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00002576 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002577 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00002578 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00002579 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002580
2581 // See if anything took the address of blocks in this function.
2582 auto BBFRI = BasicBlockFwdRefs.find(F);
2583 if (BBFRI == BasicBlockFwdRefs.end()) {
2584 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2585 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2586 } else {
2587 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002588 // Check for invalid basic block references.
2589 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002590 return Error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002591 assert(!BBRefs.empty() && "Unexpected empty array");
2592 assert(!BBRefs.front() && "Invalid reference to entry block");
2593 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2594 ++I)
2595 if (I < RE && BBRefs[I]) {
2596 BBRefs[I]->insertInto(F);
2597 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002598 } else {
2599 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2600 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002601
2602 // Erase from the table.
2603 BasicBlockFwdRefs.erase(BBFRI);
2604 }
2605
Chris Lattner83930552007-05-01 07:01:57 +00002606 CurBB = FunctionBBs[0];
2607 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002608 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002609
Chris Lattner07d09ed2010-04-03 02:17:50 +00002610 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2611 // This record indicates that the last instruction is at the same
2612 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002613 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002614
Craig Topper2617dcc2014-04-15 06:32:26 +00002615 if (!I)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002616 return Error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00002617 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002618 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002619 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002620
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00002621 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002622 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00002623 if (!I || Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002624 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002625
Chris Lattner07d09ed2010-04-03 02:17:50 +00002626 unsigned Line = Record[0], Col = Record[1];
2627 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002628
Craig Topper2617dcc2014-04-15 06:32:26 +00002629 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002630 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2631 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2632 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2633 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002634 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002635 continue;
2636 }
2637
Chris Lattnere9759c22007-05-06 00:21:25 +00002638 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2639 unsigned OpNum = 0;
2640 Value *LHS, *RHS;
2641 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002642 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00002643 OpNum+1 > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002644 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002645
Dan Gohman0ebd6962009-07-20 21:19:07 +00002646 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00002647 if (Opc == -1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002648 return Error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002649 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00002650 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00002651 if (OpNum < Record.size()) {
2652 if (Opc == Instruction::Add ||
2653 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002654 Opc == Instruction::Mul ||
2655 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00002656 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00002657 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00002658 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00002659 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00002660 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002661 Opc == Instruction::UDiv ||
2662 Opc == Instruction::LShr ||
2663 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002664 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002665 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002666 } else if (isa<FPMathOperator>(I)) {
2667 FastMathFlags FMF;
Michael Ilseman65f14352012-12-09 21:12:04 +00002668 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2669 FMF.setUnsafeAlgebra();
2670 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2671 FMF.setNoNaNs();
2672 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2673 FMF.setNoInfs();
2674 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2675 FMF.setNoSignedZeros();
2676 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2677 FMF.setAllowReciprocal();
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002678 if (FMF.any())
2679 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00002680 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002681
Dan Gohman1b849082009-09-07 23:54:19 +00002682 }
Chris Lattner85b7b402007-05-01 05:52:21 +00002683 break;
2684 }
Chris Lattnere9759c22007-05-06 00:21:25 +00002685 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2686 unsigned OpNum = 0;
2687 Value *Op;
2688 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2689 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002690 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002691
Chris Lattner229907c2011-07-18 04:54:35 +00002692 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnere9759c22007-05-06 00:21:25 +00002693 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002694 if (Opc == -1 || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002695 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00002696 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002697 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2698 if (Temp) {
2699 InstructionList.push_back(Temp);
2700 CurBB->getInstList().push_back(Temp);
2701 }
2702 } else {
2703 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2704 }
Devang Patelaf206b82009-09-18 19:26:43 +00002705 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00002706 break;
2707 }
Dan Gohman1639c392009-07-27 21:53:46 +00002708 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattnere14cb882007-05-04 19:11:41 +00002709 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002710 unsigned OpNum = 0;
2711 Value *BasePtr;
2712 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002713 return Error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00002714
Chris Lattner5285b5e2007-05-02 05:46:45 +00002715 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002716 while (OpNum != Record.size()) {
2717 Value *Op;
2718 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002719 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002720 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002721 }
2722
Jay Foadd1b78492011-07-25 09:48:08 +00002723 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002724 InstructionList.push_back(I);
Dan Gohman1639c392009-07-27 21:53:46 +00002725 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohman1b849082009-09-07 23:54:19 +00002726 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002727 break;
2728 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002729
Dan Gohman1ecaf452008-05-31 00:58:22 +00002730 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2731 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00002732 unsigned OpNum = 0;
2733 Value *Agg;
2734 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002735 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00002736
Dan Gohman1ecaf452008-05-31 00:58:22 +00002737 SmallVector<unsigned, 4> EXTRACTVALIdx;
2738 for (unsigned RecSize = Record.size();
2739 OpNum != RecSize; ++OpNum) {
2740 uint64_t Index = Record[OpNum];
2741 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002742 return Error("Invalid value");
Dan Gohman1ecaf452008-05-31 00:58:22 +00002743 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohman30499842008-05-23 01:55:30 +00002744 }
2745
Jay Foad57aa6362011-07-13 10:26:04 +00002746 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002747 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00002748 break;
2749 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750
Dan Gohman1ecaf452008-05-31 00:58:22 +00002751 case bitc::FUNC_CODE_INST_INSERTVAL: {
2752 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00002753 unsigned OpNum = 0;
2754 Value *Agg;
2755 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002756 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00002757 Value *Val;
2758 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002759 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00002760
Dan Gohman1ecaf452008-05-31 00:58:22 +00002761 SmallVector<unsigned, 4> INSERTVALIdx;
2762 for (unsigned RecSize = Record.size();
2763 OpNum != RecSize; ++OpNum) {
2764 uint64_t Index = Record[OpNum];
2765 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002766 return Error("Invalid value");
Dan Gohman1ecaf452008-05-31 00:58:22 +00002767 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohman30499842008-05-23 01:55:30 +00002768 }
2769
Jay Foad57aa6362011-07-13 10:26:04 +00002770 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002771 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00002772 break;
2773 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
Chris Lattnere9759c22007-05-06 00:21:25 +00002775 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00002776 // obsolete form of select
2777 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00002778 unsigned OpNum = 0;
2779 Value *TrueVal, *FalseVal, *Cond;
2780 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002781 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2782 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002783 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002784
Dan Gohmanc5d28922008-09-16 01:01:33 +00002785 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00002786 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00002787 break;
2788 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002789
Dan Gohmanc5d28922008-09-16 01:01:33 +00002790 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2791 // new form of select
2792 // handles select i1 or select [N x i1]
2793 unsigned OpNum = 0;
2794 Value *TrueVal, *FalseVal, *Cond;
2795 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002796 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00002797 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002798 return Error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00002799
2800 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00002801 if (VectorType* vector_type =
2802 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00002803 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002804 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002805 return Error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00002806 } else {
2807 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002808 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002809 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002810 }
2811
Gabor Greife9ecc682008-04-06 20:25:17 +00002812 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00002813 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002814 break;
2815 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002816
Chris Lattner1fc27f02007-05-02 05:16:49 +00002817 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00002818 unsigned OpNum = 0;
2819 Value *Vec, *Idx;
2820 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002821 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002822 return Error("Invalid record");
Eric Christopherc9742252009-07-25 02:28:41 +00002823 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00002824 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002825 break;
2826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002827
Chris Lattner1fc27f02007-05-02 05:16:49 +00002828 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00002829 unsigned OpNum = 0;
2830 Value *Vec, *Elt, *Idx;
2831 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002832 popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00002833 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002834 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002835 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00002836 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00002837 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002838 break;
2839 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002840
Chris Lattnere9759c22007-05-06 00:21:25 +00002841 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2842 unsigned OpNum = 0;
2843 Value *Vec1, *Vec2, *Mask;
2844 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002845 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002846 return Error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00002847
Mon P Wang25f01062008-11-10 04:46:22 +00002848 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002849 return Error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00002850 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00002851 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002852 break;
2853 }
Mon P Wang25f01062008-11-10 04:46:22 +00002854
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002855 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2856 // Old form of ICmp/FCmp returning bool
2857 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2858 // both legal on vectors but had different behaviour.
2859 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2860 // FCmp/ICmp returning bool or vector of bool
2861
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002862 unsigned OpNum = 0;
2863 Value *LHS, *RHS;
2864 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002865 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002866 OpNum+1 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002867 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Duncan Sands9dff9be2010-02-15 16:12:20 +00002869 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohmanad1f0a12009-08-25 23:17:54 +00002870 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002871 else
Dan Gohmanad1f0a12009-08-25 23:17:54 +00002872 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00002873 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00002874 break;
2875 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002876
Chris Lattnere53603e2007-05-02 04:27:25 +00002877 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00002878 {
2879 unsigned Size = Record.size();
2880 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002881 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002882 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00002883 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002884 }
Devang Patelbbfd8742008-02-26 01:29:32 +00002885
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002886 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00002887 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00002888 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002889 return Error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00002890 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002891 return Error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002892
Chris Lattnerf1c87102011-06-17 18:09:11 +00002893 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002894 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002895 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00002896 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00002897 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00002898 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002899 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00002900 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002901 if (!TrueDest)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002902 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00002903
Devang Patelaf206b82009-09-18 19:26:43 +00002904 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00002905 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002906 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00002907 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00002908 else {
2909 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002910 Value *Cond = getValue(Record, 2, NextValueNo,
2911 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00002912 if (!FalseDest || !Cond)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002913 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00002914 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002915 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002916 }
2917 break;
2918 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00002919 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002920 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002921 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00002922 // "New" SwitchInst format with case ranges. The changes to write this
2923 // format were reverted but we still recognize bitcode that uses it.
2924 // Hopefully someday we will have support for case ranges and can use
2925 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002926
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002927 Type *OpTy = getTypeByID(Record[1]);
2928 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2929
Jan Wen Voungafaced02012-10-11 20:20:40 +00002930 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002931 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002932 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002933 return Error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002934
2935 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002936
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002937 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2938 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002939
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002940 unsigned CurIdx = 5;
2941 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00002942 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002943 unsigned NumItems = Record[CurIdx++];
2944 for (unsigned ci = 0; ci != NumItems; ++ci) {
2945 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002946
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002947 APInt Low;
2948 unsigned ActiveWords = 1;
2949 if (ValueBitWidth > 64)
2950 ActiveWords = Record[CurIdx++];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002951 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2952 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002953 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00002954
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002955 if (!isSingleNumber) {
2956 ActiveWords = 1;
2957 if (ValueBitWidth > 64)
2958 ActiveWords = Record[CurIdx++];
2959 APInt High =
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002960 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2961 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002962 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00002963
2964 // FIXME: It is not clear whether values in the range should be
2965 // compared as signed or unsigned values. The partially
2966 // implemented changes that used this format in the past used
2967 // unsigned comparisons.
2968 for ( ; Low.ule(High); ++Low)
2969 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002970 } else
Bob Wilsone4077362013-09-09 19:14:35 +00002971 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002972 }
2973 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00002974 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2975 cve = CaseVals.end(); cvi != cve; ++cvi)
2976 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002977 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002978 I = SI;
2979 break;
2980 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002981
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002982 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002983
Chris Lattner5285b5e2007-05-02 05:46:45 +00002984 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002985 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002986 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002987 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002988 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002989 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002990 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00002991 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00002992 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00002993 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002994 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002995 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00002996 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2997 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002998 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00002999 delete SI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003000 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003001 }
3002 SI->addCase(CaseVal, DestBB);
3003 }
3004 I = SI;
3005 break;
3006 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003007 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00003008 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003009 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003010 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003011 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003012 if (!OpTy || !Address)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003013 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003014 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003015 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00003016 InstructionList.push_back(IBI);
3017 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3018 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3019 IBI->addDestination(DestBB);
3020 } else {
3021 delete IBI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003022 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003023 }
3024 }
3025 I = IBI;
3026 break;
3027 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003028
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003029 case bitc::FUNC_CODE_INST_INVOKE: {
3030 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003031 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003032 return Error("Invalid record");
Bill Wendlinge94d8432012-12-07 23:16:57 +00003033 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003034 unsigned CCInfo = Record[1];
3035 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3036 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003037
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003038 unsigned OpNum = 4;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003039 Value *Callee;
3040 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003041 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003042
Chris Lattner229907c2011-07-18 04:54:35 +00003043 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00003044 FunctionType *FTy = !CalleeTy ? nullptr :
Chris Lattner5285b5e2007-05-02 05:46:45 +00003045 dyn_cast<FunctionType>(CalleeTy->getElementType());
3046
3047 // Check that the right number of fixed parameters are here.
Craig Topper2617dcc2014-04-15 06:32:26 +00003048 if (!FTy || !NormalBB || !UnwindBB ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003049 Record.size() < OpNum+FTy->getNumParams())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003050 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003051
Chris Lattner5285b5e2007-05-02 05:46:45 +00003052 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003053 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003054 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3055 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003056 if (!Ops.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003057 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003058 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003059
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003060 if (!FTy->isVarArg()) {
3061 if (Record.size() != OpNum)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003062 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003063 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003064 // Read type/value pairs for varargs params.
3065 while (OpNum != Record.size()) {
3066 Value *Op;
3067 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003068 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003069 Ops.push_back(Op);
3070 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003071 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003072
Jay Foad5bd375a2011-07-15 08:37:34 +00003073 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00003074 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003075 cast<InvokeInst>(I)->setCallingConv(
3076 static_cast<CallingConv::ID>(CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00003077 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003078 break;
3079 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00003080 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3081 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003082 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003083 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003084 return Error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00003085 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00003086 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003087 break;
3088 }
Chris Lattnere53603e2007-05-02 04:27:25 +00003089 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00003090 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00003091 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003092 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00003093 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00003094 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003095 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003096 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003097 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003098 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003099
Jay Foad52131342011-03-30 11:28:46 +00003100 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00003101 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003102
Chris Lattnere14cb882007-05-04 19:11:41 +00003103 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003104 Value *V;
3105 // With the new function encoding, it is possible that operands have
3106 // negative IDs (for forward references). Use a signed VBR
3107 // representation to keep the encoding small.
3108 if (UseRelativeIDs)
3109 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3110 else
3111 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00003112 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003113 if (!V || !BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003114 return Error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00003115 PN->addIncoming(V, BB);
3116 }
3117 I = PN;
3118 break;
3119 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003120
Bill Wendlingfae14752011-08-12 20:24:12 +00003121 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3122 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3123 unsigned Idx = 0;
3124 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003125 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003126 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003127 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003128 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003129 Value *PersFn = nullptr;
Bill Wendlingfae14752011-08-12 20:24:12 +00003130 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003131 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003132
3133 bool IsCleanup = !!Record[Idx++];
3134 unsigned NumClauses = Record[Idx++];
3135 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3136 LP->setCleanup(IsCleanup);
3137 for (unsigned J = 0; J != NumClauses; ++J) {
3138 LandingPadInst::ClauseType CT =
3139 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3140 Value *Val;
3141
3142 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3143 delete LP;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003144 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003145 }
3146
3147 assert((CT != LandingPadInst::Catch ||
3148 !isa<ArrayType>(Val->getType())) &&
3149 "Catch clause has a invalid type!");
3150 assert((CT != LandingPadInst::Filter ||
3151 isa<ArrayType>(Val->getType())) &&
3152 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00003153 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00003154 }
3155
3156 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00003157 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00003158 break;
3159 }
3160
Chris Lattnerf1c87102011-06-17 18:09:11 +00003161 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3162 if (Record.size() != 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003163 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003164 PointerType *Ty =
Chris Lattnerc332bba2007-05-03 18:58:09 +00003165 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattner229907c2011-07-18 04:54:35 +00003166 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerf1c87102011-06-17 18:09:11 +00003167 Value *Size = getFnValueByID(Record[2], OpTy);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00003168 unsigned AlignRecord = Record[3];
3169 bool InAlloca = AlignRecord & (1 << 5);
3170 unsigned Align = AlignRecord & ((1 << 5) - 1);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003171 if (!Ty || !Size)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003172 return Error("Invalid record");
Reid Kleckner56b56ea2014-07-16 01:34:27 +00003173 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3174 AI->setUsedWithInAlloca(InAlloca);
3175 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00003176 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00003177 break;
3178 }
Chris Lattner9f600c52007-05-03 22:04:19 +00003179 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003180 unsigned OpNum = 0;
3181 Value *Op;
3182 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3183 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003184 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003185
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003186 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patelaf206b82009-09-18 19:26:43 +00003187 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00003188 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00003189 }
Eli Friedman59b66882011-08-09 23:02:53 +00003190 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3191 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3192 unsigned OpNum = 0;
3193 Value *Op;
3194 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3195 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003196 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003197
3198 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3199 if (Ordering == NotAtomic || Ordering == Release ||
3200 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003201 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003202 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003203 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003204 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3205
3206 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3207 Ordering, SynchScope);
3208 InstructionList.push_back(I);
3209 break;
3210 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003211 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003212 unsigned OpNum = 0;
3213 Value *Val, *Ptr;
3214 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003215 popValue(Record, OpNum, NextValueNo,
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003216 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3217 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003218 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003219
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003220 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patelaf206b82009-09-18 19:26:43 +00003221 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003222 break;
3223 }
Eli Friedman59b66882011-08-09 23:02:53 +00003224 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3225 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3226 unsigned OpNum = 0;
3227 Value *Val, *Ptr;
3228 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003229 popValue(Record, OpNum, NextValueNo,
Eli Friedman59b66882011-08-09 23:02:53 +00003230 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3231 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003232 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003233
3234 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00003235 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00003236 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003237 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003238 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3239 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003240 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00003241
3242 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3243 Ordering, SynchScope);
3244 InstructionList.push_back(I);
3245 break;
3246 }
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003247 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00003248 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00003249 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003250 unsigned OpNum = 0;
3251 Value *Ptr, *Cmp, *New;
3252 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003253 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003254 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003255 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003256 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
Tim Northover420a2162014-06-13 14:24:07 +00003257 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003258 return Error("Invalid record");
Tim Northovere94a5182014-03-11 10:48:52 +00003259 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3260 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003261 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003262 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
Tim Northovere94a5182014-03-11 10:48:52 +00003263
3264 AtomicOrdering FailureOrdering;
3265 if (Record.size() < 7)
3266 FailureOrdering =
3267 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3268 else
3269 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3270
3271 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3272 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003273 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00003274
3275 if (Record.size() < 8) {
3276 // Before weak cmpxchgs existed, the instruction simply returned the
3277 // value loaded from memory, so bitcode files from that era will be
3278 // expecting the first component of a modern cmpxchg.
3279 CurBB->getInstList().push_back(I);
3280 I = ExtractValueInst::Create(I, 0);
3281 } else {
3282 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3283 }
3284
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003285 InstructionList.push_back(I);
3286 break;
3287 }
3288 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3289 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3290 unsigned OpNum = 0;
3291 Value *Ptr, *Val;
3292 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003293 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003294 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3295 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003296 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003297 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3298 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3299 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003300 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003301 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman59b66882011-08-09 23:02:53 +00003302 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003303 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003304 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3305 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3306 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3307 InstructionList.push_back(I);
3308 break;
3309 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00003310 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3311 if (2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003312 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00003313 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3314 if (Ordering == NotAtomic || Ordering == Unordered ||
3315 Ordering == Monotonic)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003316 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00003317 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3318 I = new FenceInst(Context, Ordering, SynchScope);
3319 InstructionList.push_back(I);
3320 break;
3321 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003322 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003323 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3324 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003325 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003326
Bill Wendlinge94d8432012-12-07 23:16:57 +00003327 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003328 unsigned CCInfo = Record[1];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003329
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003330 unsigned OpNum = 2;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003331 Value *Callee;
3332 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003333 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003334
Chris Lattner229907c2011-07-18 04:54:35 +00003335 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00003336 FunctionType *FTy = nullptr;
Chris Lattner9f600c52007-05-03 22:04:19 +00003337 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003338 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003339 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003340
Chris Lattner9f600c52007-05-03 22:04:19 +00003341 SmallVector<Value*, 16> Args;
3342 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003343 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003344 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00003345 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00003346 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00003347 Args.push_back(getValue(Record, OpNum, NextValueNo,
3348 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003349 if (!Args.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003350 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00003351 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003352
Chris Lattner9f600c52007-05-03 22:04:19 +00003353 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00003354 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003355 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003356 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00003357 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003358 while (OpNum != Record.size()) {
3359 Value *Op;
3360 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003361 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003362 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00003363 }
3364 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003365
Jay Foad5bd375a2011-07-15 08:37:34 +00003366 I = CallInst::Create(Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00003367 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003368 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00003369 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3370 CallInst::TailCallKind TCK = CallInst::TCK_None;
3371 if (CCInfo & 1)
3372 TCK = CallInst::TCK_Tail;
3373 if (CCInfo & (1 << 14))
3374 TCK = CallInst::TCK_MustTail;
3375 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00003376 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00003377 break;
3378 }
3379 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3380 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003381 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003382 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003383 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003384 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00003385 if (!OpTy || !Op || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003386 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00003387 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00003388 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00003389 break;
3390 }
Chris Lattner83930552007-05-01 07:01:57 +00003391 }
3392
3393 // Add instruction to end of current BB. If there is no current BB, reject
3394 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00003395 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00003396 delete I;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003397 return Error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00003398 }
3399 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003400
Chris Lattner83930552007-05-01 07:01:57 +00003401 // If this was a terminator instruction, move to the next block.
3402 if (isa<TerminatorInst>(I)) {
3403 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00003404 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00003405 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003406
Chris Lattner83930552007-05-01 07:01:57 +00003407 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003408 if (I && !I->getType()->isVoidTy())
Chris Lattner83930552007-05-01 07:01:57 +00003409 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00003410 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003411
Chris Lattner27d38752013-01-20 02:13:19 +00003412OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00003413
Chris Lattner83930552007-05-01 07:01:57 +00003414 // Check the function list for unresolved values.
3415 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003416 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00003417 // We found at least one unresolved value. Nuke them all to avoid leaks.
3418 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00003419 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003420 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00003421 delete A;
3422 }
3423 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003424 return Error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00003425 }
Chris Lattner83930552007-05-01 07:01:57 +00003426 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003427
Dan Gohman9b9ff462010-08-25 20:23:38 +00003428 // FIXME: Check for unresolved forward-declared metadata references
3429 // and clean up leaks.
3430
Chris Lattner85b7b402007-05-01 05:52:21 +00003431 // Trim the value list down to the size it was before we parsed this function.
3432 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00003433 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00003434 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003435 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003436}
3437
Rafael Espindola7d712032013-11-05 17:16:08 +00003438/// Find the function body in the bitcode stream
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003439std::error_code BitcodeReader::FindFunctionInStream(
3440 Function *F,
3441 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003442 while (DeferredFunctionInfoIterator->second == 0) {
3443 if (Stream.AtEndOfStream())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003444 return Error("Could not find function in stream");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003445 // ParseModule will parse the next body in the stream and set its
3446 // position in the DeferredFunctionInfo map.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003447 if (std::error_code EC = ParseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00003448 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003449 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003450 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003451}
3452
Chris Lattner9eeada92007-05-18 04:02:46 +00003453//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003454// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00003455//===----------------------------------------------------------------------===//
3456
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00003457void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00003458
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00003459std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003460 Function *F = dyn_cast<Function>(GV);
3461 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003462 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003463 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003464
3465 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00003466 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003467 // If its position is recorded as 0, its body is somewhere in the stream
3468 // but we haven't seen it yet.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003469 if (DFII->second == 0 && LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003470 if (std::error_code EC = FindFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003471 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003472
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003473 // Move the bit stream to the saved position of the deferred function body.
3474 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003475
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003476 if (std::error_code EC = ParseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003477 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003478 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00003479
3480 // Upgrade any old intrinsic calls in the function.
3481 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3482 E = UpgradedIntrinsics.end(); I != E; ++I) {
3483 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003484 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3485 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003486 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3487 UpgradeIntrinsicCall(CI, I->second);
3488 }
3489 }
3490 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003491
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003492 // Bring in any functions that this function forward-referenced via
3493 // blockaddresses.
3494 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00003495}
3496
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003497bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3498 const Function *F = dyn_cast<Function>(GV);
3499 if (!F || F->isDeclaration())
3500 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003501
3502 // Dematerializing F would leave dangling references that wouldn't be
3503 // reconnected on re-materialization.
3504 if (BlockAddressesTaken.count(F))
3505 return false;
3506
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003507 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3508}
3509
3510void BitcodeReader::Dematerialize(GlobalValue *GV) {
3511 Function *F = dyn_cast<Function>(GV);
3512 // If this function isn't dematerializable, this is a noop.
3513 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00003514 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003515
Chris Lattner9eeada92007-05-18 04:02:46 +00003516 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003517
Chris Lattner9eeada92007-05-18 04:02:46 +00003518 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00003519 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003520 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00003521}
3522
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003523std::error_code BitcodeReader::MaterializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003524 assert(M == TheModule &&
3525 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003526
3527 // Promise to materialize all forward references.
3528 WillMaterializeAllForwardRefs = true;
3529
Chris Lattner06310bf2009-06-16 05:15:21 +00003530 // Iterate over the module, deserializing any functions that are still on
3531 // disk.
3532 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003533 F != E; ++F) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +00003534 if (std::error_code EC = materialize(F))
3535 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003536 }
Derek Schuff92ef9752012-02-29 00:07:09 +00003537 // At this point, if there are any function bodies, the current bit is
3538 // pointing to the END_BLOCK record after them. Now make sure the rest
3539 // of the bits in the module have been read.
3540 if (NextUnreadBit)
3541 ParseModule(true);
3542
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003543 // Check that all block address forward references got resolved (as we
3544 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003545 if (!BasicBlockFwdRefs.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003546 return Error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003547
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003548 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3549 // delete the old functions to clean up. We can't do this unless the entire
3550 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00003551 // with calls to the old function.
3552 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3553 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3554 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003555 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3556 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003557 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3558 UpgradeIntrinsicCall(CI, I->second);
3559 }
Chris Lattner647cffb2009-04-01 01:43:03 +00003560 if (!I->first->use_empty())
3561 I->first->replaceAllUsesWith(I->second);
Chandler Carruth7132e002007-08-04 01:51:18 +00003562 I->first->eraseFromParent();
3563 }
3564 }
3565 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patel80ae3492009-08-28 23:24:31 +00003566
Manman Ren209b17c2013-09-28 00:22:27 +00003567 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3568 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3569
Manman Ren8b4306c2013-12-02 21:29:56 +00003570 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003571 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00003572}
3573
Rafael Espindola2fa1e432014-12-03 07:18:23 +00003574std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3575 return IdentifiedStructTypes;
3576}
3577
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003578std::error_code BitcodeReader::InitStream() {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003579 if (LazyStreamer)
3580 return InitLazyStream();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003581 return InitStreamFromBuffer();
3582}
3583
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003584std::error_code BitcodeReader::InitStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00003585 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003586 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3587
Rafael Espindola27435252014-07-29 21:01:24 +00003588 if (Buffer->getBufferSize() & 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003589 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003590
3591 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3592 // The magic number is 0x0B17C0DE stored in little endian.
3593 if (isBitcodeWrapper(BufPtr, BufEnd))
3594 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003595 return Error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003596
3597 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00003598 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003599
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003600 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003601}
3602
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003603std::error_code BitcodeReader::InitLazyStream() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003604 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3605 // see it.
Yaron Keren06d69302014-12-18 10:03:35 +00003606 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
Rafael Espindola7d727b52014-12-18 05:08:43 +00003607 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00003608 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00003609 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003610
3611 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00003612 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003613 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003614
3615 if (!isBitcode(buf, buf + 16))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003616 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003617
3618 if (isBitcodeWrapper(buf, buf + 4)) {
3619 const unsigned char *bitcodeStart = buf;
3620 const unsigned char *bitcodeEnd = buf + 16;
3621 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00003622 Bytes.dropLeadingBytes(bitcodeStart - buf);
3623 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003624 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003625 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00003626}
3627
3628namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00003629class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00003630 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003631 return "llvm.bitcode";
3632 }
Craig Topper73156022014-03-02 09:09:27 +00003633 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003634 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003635 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003636 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003637 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003638 case BitcodeError::CorruptedBitcode:
3639 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00003640 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00003641 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00003642 }
3643};
3644}
3645
Chris Bieneman770163e2014-09-19 20:29:02 +00003646static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3647
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003648const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00003649 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003650}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003651
Chris Lattner6694f602007-04-29 07:54:31 +00003652//===----------------------------------------------------------------------===//
3653// External interface
3654//===----------------------------------------------------------------------===//
3655
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003656/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00003657///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003658/// This isn't always used in a lazy context. In particular, it's also used by
3659/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3660/// in forward-referenced functions from block address references.
3661///
3662/// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3663/// materialize everything -- in particular, if this isn't truly lazy.
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003664static ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00003665getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003666 LLVMContext &Context, bool WillMaterializeAll,
3667 DiagnosticHandlerFunction DiagnosticHandler) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003668 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003669 BitcodeReader *R =
3670 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003671 M->setMaterializer(R);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003672
3673 auto cleanupOnError = [&](std::error_code EC) {
Rafael Espindola8fb31112014-06-18 20:07:35 +00003674 R->releaseBuffer(); // Never take ownership on error.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003675 delete M; // Also deletes R.
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00003676 return EC;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003677 };
Rafael Espindolab7993462012-01-02 07:49:53 +00003678
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003679 if (std::error_code EC = R->ParseBitcodeInto(M))
3680 return cleanupOnError(EC);
3681
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003682 if (!WillMaterializeAll)
3683 // Resolve forward references from blockaddresses.
3684 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3685 return cleanupOnError(EC);
Rafael Espindolab7993462012-01-02 07:49:53 +00003686
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003687 Buffer.release(); // The BitcodeReader owns it now.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003688 return M;
Chris Lattner6694f602007-04-29 07:54:31 +00003689}
3690
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003691ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00003692llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003693 LLVMContext &Context,
3694 DiagnosticHandlerFunction DiagnosticHandler) {
3695 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3696 DiagnosticHandler);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003697}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003698
Rafael Espindola7d727b52014-12-18 05:08:43 +00003699ErrorOr<std::unique_ptr<Module>>
3700llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003701 LLVMContext &Context,
3702 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00003703 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003704 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003705 M->setMaterializer(R);
Rafael Espindola7d727b52014-12-18 05:08:43 +00003706 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3707 return EC;
3708 return std::move(M);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003709}
3710
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003711ErrorOr<Module *>
3712llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3713 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00003714 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003715 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3716 std::move(Buf), Context, true, DiagnosticHandler);
Rafael Espindola8f31e212014-01-15 01:08:23 +00003717 if (!ModuleOrErr)
3718 return ModuleOrErr;
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00003719 Module *M = ModuleOrErr.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003720 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolad96d5532014-08-26 21:49:01 +00003721 if (std::error_code EC = M->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003722 delete M;
Rafael Espindola8f31e212014-01-15 01:08:23 +00003723 return EC;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003724 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003725
Chad Rosierca2567b2011-12-07 21:44:12 +00003726 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3727 // written. We must defer until the Module has been fully materialized.
3728
Chris Lattner6694f602007-04-29 07:54:31 +00003729 return M;
3730}
Bill Wendling0198ce02010-10-06 01:22:42 +00003731
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003732std::string
3733llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3734 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00003735 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003736 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3737 DiagnosticHandler);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003738 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00003739 if (Triple.getError())
3740 return "";
3741 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00003742}