blob: 507164c8468b13fe6feef5c80dbb30a711bbaea8 [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"
18#include "llvm/IR/InlineAsm.h"
19#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000020#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Module.h"
22#include "llvm/IR/OperandTraits.h"
23#include "llvm/IR/Operator.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000024#include "llvm/Support/DataStream.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000027#include "llvm/Support/raw_ostream.h"
Chris Bieneman770163e2014-09-19 20:29:02 +000028#include "llvm/Support/ManagedStatic.h"
29
Chris Lattner1314b992007-04-22 06:23:29 +000030using namespace llvm;
31
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000032enum {
33 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34};
35
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000036std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
37 if (WillMaterializeAllForwardRefs)
38 return std::error_code();
39
40 // Prevent recursion.
41 WillMaterializeAllForwardRefs = true;
42
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000043 while (!BasicBlockFwdRefQueue.empty()) {
44 Function *F = BasicBlockFwdRefQueue.front();
45 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000046 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000047 if (!BasicBlockFwdRefs.count(F))
48 // Already materialized.
49 continue;
50
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000051 // Check for a function that isn't materializable to prevent an infinite
52 // loop. When parsing a blockaddress stored in a global variable, there
53 // isn't a trivial way to check if a function will have a body without a
54 // linear search through FunctionsWithBodies, so just check it here.
55 if (!F->isMaterializable())
56 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
57
58 // Try to materialize F.
59 if (std::error_code EC = Materialize(F))
60 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +000061 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000062 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000063
64 // Reset state.
65 WillMaterializeAllForwardRefs = false;
66 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +000067}
68
Chris Lattner9eeada92007-05-18 04:02:46 +000069void BitcodeReader::FreeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +000070 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000071 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +000072 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +000073 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +000074 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000075
Bill Wendlinge94d8432012-12-07 23:16:57 +000076 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +000077 std::vector<BasicBlock*>().swap(FunctionBBs);
78 std::vector<Function*>().swap(FunctionsWithBodies);
79 DeferredFunctionInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +000080 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +000081
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +000082 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000083 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +000084}
85
Chris Lattnerfee5a372007-05-04 03:30:17 +000086//===----------------------------------------------------------------------===//
87// Helper functions to implement forward reference resolution, etc.
88//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +000089
Chris Lattner1314b992007-04-22 06:23:29 +000090/// ConvertToString - Convert a string from a record into an std::string, return
91/// true on failure.
Chris Lattnerccaa4482007-04-23 21:26:05 +000092template<typename StrTy>
Benjamin Kramer9704ed02012-05-28 14:10:31 +000093static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +000094 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +000095 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +000096 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000097
Chris Lattnere14cb882007-05-04 19:11:41 +000098 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
99 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000100 return false;
101}
102
103static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
104 switch (Val) {
105 default: // Map unknown/new linkages to external
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +0000106 case 0: return GlobalValue::ExternalLinkage;
107 case 1: return GlobalValue::WeakAnyLinkage;
108 case 2: return GlobalValue::AppendingLinkage;
109 case 3: return GlobalValue::InternalLinkage;
110 case 4: return GlobalValue::LinkOnceAnyLinkage;
Nico Rieck7157bb72014-01-14 15:22:47 +0000111 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
112 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
Bill Wendlinga3c6f6b2009-07-20 01:03:30 +0000113 case 7: return GlobalValue::ExternalWeakLinkage;
114 case 8: return GlobalValue::CommonLinkage;
115 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands12da8ce2009-03-07 15:45:40 +0000116 case 10: return GlobalValue::WeakODRLinkage;
117 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner184f1be2009-04-13 05:44:34 +0000118 case 12: return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000119 case 13:
120 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
121 case 14:
122 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Chris Lattner1314b992007-04-22 06:23:29 +0000123 }
124}
125
126static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
127 switch (Val) {
128 default: // Map unknown visibilities to default.
129 case 0: return GlobalValue::DefaultVisibility;
130 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000131 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000132 }
133}
134
Nico Rieck7157bb72014-01-14 15:22:47 +0000135static GlobalValue::DLLStorageClassTypes
136GetDecodedDLLStorageClass(unsigned Val) {
137 switch (Val) {
138 default: // Map unknown values to default.
139 case 0: return GlobalValue::DefaultStorageClass;
140 case 1: return GlobalValue::DLLImportStorageClass;
141 case 2: return GlobalValue::DLLExportStorageClass;
142 }
143}
144
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000145static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
146 switch (Val) {
147 case 0: return GlobalVariable::NotThreadLocal;
148 default: // Map unknown non-zero value to general dynamic.
149 case 1: return GlobalVariable::GeneralDynamicTLSModel;
150 case 2: return GlobalVariable::LocalDynamicTLSModel;
151 case 3: return GlobalVariable::InitialExecTLSModel;
152 case 4: return GlobalVariable::LocalExecTLSModel;
153 }
154}
155
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000156static int GetDecodedCastOpcode(unsigned Val) {
157 switch (Val) {
158 default: return -1;
159 case bitc::CAST_TRUNC : return Instruction::Trunc;
160 case bitc::CAST_ZEXT : return Instruction::ZExt;
161 case bitc::CAST_SEXT : return Instruction::SExt;
162 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
163 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
164 case bitc::CAST_UITOFP : return Instruction::UIToFP;
165 case bitc::CAST_SITOFP : return Instruction::SIToFP;
166 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
167 case bitc::CAST_FPEXT : return Instruction::FPExt;
168 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
169 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
170 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000171 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000172 }
173}
Chris Lattner229907c2011-07-18 04:54:35 +0000174static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000175 switch (Val) {
176 default: return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000177 case bitc::BINOP_ADD:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000178 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000179 case bitc::BINOP_SUB:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000180 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000181 case bitc::BINOP_MUL:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000182 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000183 case bitc::BINOP_UDIV: return Instruction::UDiv;
184 case bitc::BINOP_SDIV:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000185 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000186 case bitc::BINOP_UREM: return Instruction::URem;
187 case bitc::BINOP_SREM:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000188 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000189 case bitc::BINOP_SHL: return Instruction::Shl;
190 case bitc::BINOP_LSHR: return Instruction::LShr;
191 case bitc::BINOP_ASHR: return Instruction::AShr;
192 case bitc::BINOP_AND: return Instruction::And;
193 case bitc::BINOP_OR: return Instruction::Or;
194 case bitc::BINOP_XOR: return Instruction::Xor;
195 }
196}
197
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000198static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
199 switch (Val) {
200 default: return AtomicRMWInst::BAD_BINOP;
201 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
202 case bitc::RMW_ADD: return AtomicRMWInst::Add;
203 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
204 case bitc::RMW_AND: return AtomicRMWInst::And;
205 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
206 case bitc::RMW_OR: return AtomicRMWInst::Or;
207 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
208 case bitc::RMW_MAX: return AtomicRMWInst::Max;
209 case bitc::RMW_MIN: return AtomicRMWInst::Min;
210 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
211 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
212 }
213}
214
Eli Friedmanfee02c62011-07-25 23:16:38 +0000215static AtomicOrdering GetDecodedOrdering(unsigned Val) {
216 switch (Val) {
217 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
218 case bitc::ORDERING_UNORDERED: return Unordered;
219 case bitc::ORDERING_MONOTONIC: return Monotonic;
220 case bitc::ORDERING_ACQUIRE: return Acquire;
221 case bitc::ORDERING_RELEASE: return Release;
222 case bitc::ORDERING_ACQREL: return AcquireRelease;
223 default: // Map unknown orderings to sequentially-consistent.
224 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
225 }
226}
227
228static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
229 switch (Val) {
230 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
231 default: // Map unknown scopes to cross-thread.
232 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
233 }
234}
235
David Majnemerdad0a642014-06-27 18:19:56 +0000236static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
237 switch (Val) {
238 default: // Map unknown selection kinds to any.
239 case bitc::COMDAT_SELECTION_KIND_ANY:
240 return Comdat::Any;
241 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
242 return Comdat::ExactMatch;
243 case bitc::COMDAT_SELECTION_KIND_LARGEST:
244 return Comdat::Largest;
245 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
246 return Comdat::NoDuplicates;
247 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
248 return Comdat::SameSize;
249 }
250}
251
Nico Rieck7157bb72014-01-14 15:22:47 +0000252static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
253 switch (Val) {
254 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
255 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
256 }
257}
258
Gabor Greiff6caff662008-05-10 08:32:32 +0000259namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000260namespace {
261 /// @brief A class for maintaining the slot number definition
262 /// as a placeholder for the actual definition for forward constants defs.
263 class ConstantPlaceHolder : public ConstantExpr {
Craig Toppera60c0f12012-09-15 17:09:36 +0000264 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greife9ecc682008-04-06 20:25:17 +0000265 public:
266 // allocate space for exactly one operand
267 void *operator new(size_t s) {
268 return User::operator new(s, 1);
269 }
Chris Lattner229907c2011-07-18 04:54:35 +0000270 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000271 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000272 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner1663cca2007-04-24 05:48:56 +0000273 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000274
Chris Lattner74429932008-08-21 02:34:16 +0000275 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner74429932008-08-21 02:34:16 +0000276 static bool classof(const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000277 return isa<ConstantExpr>(V) &&
Chris Lattner74429932008-08-21 02:34:16 +0000278 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
279 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000280
281
Gabor Greiff6caff662008-05-10 08:32:32 +0000282 /// Provide fast operand accessors
Chris Lattner2d8cd802009-03-31 22:55:09 +0000283 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner1663cca2007-04-24 05:48:56 +0000284 };
285}
286
Chris Lattner2d8cd802009-03-31 22:55:09 +0000287// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000288template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000289struct OperandTraits<ConstantPlaceHolder> :
290 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000291};
Gabor Greiff6caff662008-05-10 08:32:32 +0000292}
293
Chris Lattner2d8cd802009-03-31 22:55:09 +0000294
295void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
296 if (Idx == size()) {
297 push_back(V);
298 return;
299 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000300
Chris Lattner2d8cd802009-03-31 22:55:09 +0000301 if (Idx >= size())
302 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000303
Chris Lattner2d8cd802009-03-31 22:55:09 +0000304 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000305 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000306 OldV = V;
307 return;
308 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000309
Chris Lattner2d8cd802009-03-31 22:55:09 +0000310 // Handle constants and non-constants (e.g. instrs) differently for
311 // efficiency.
312 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
313 ResolveConstants.push_back(std::make_pair(PHC, Idx));
314 OldV = V;
315 } else {
316 // If there was a forward reference to this value, replace it.
317 Value *PrevVal = OldV;
318 OldV->replaceAllUsesWith(V);
319 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000320 }
321}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000322
Gabor Greiff6caff662008-05-10 08:32:32 +0000323
Chris Lattner1663cca2007-04-24 05:48:56 +0000324Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000325 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000326 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000327 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000328
Chris Lattner2d8cd802009-03-31 22:55:09 +0000329 if (Value *V = ValuePtrs[Idx]) {
Chris Lattner83930552007-05-01 07:01:57 +0000330 assert(Ty == V->getType() && "Type mismatch in constant table!");
331 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000332 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000333
334 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000335 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000336 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000337 return C;
338}
339
Chris Lattner229907c2011-07-18 04:54:35 +0000340Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000341 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000342 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000343
Chris Lattner2d8cd802009-03-31 22:55:09 +0000344 if (Value *V = ValuePtrs[Idx]) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000345 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
Chris Lattner83930552007-05-01 07:01:57 +0000346 return V;
347 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000348
Chris Lattner1fc27f02007-05-02 05:16:49 +0000349 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000350 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000351
Chris Lattner83930552007-05-01 07:01:57 +0000352 // Create and return a placeholder, which will later be RAUW'd.
353 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000354 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000355 return V;
356}
357
Chris Lattner74429932008-08-21 02:34:16 +0000358/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
359/// resolves any forward references. The idea behind this is that we sometimes
360/// get constants (such as large arrays) which reference *many* forward ref
361/// constants. Replacing each of these causes a lot of thrashing when
362/// building/reuniquing the constant. Instead of doing this, we look at all the
363/// uses and rewrite all the place holders at once for any constant that uses
364/// a placeholder.
365void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000367 // binary search.
368 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000369
Chris Lattner74429932008-08-21 02:34:16 +0000370 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000371
Chris Lattner74429932008-08-21 02:34:16 +0000372 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000373 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000374 Constant *Placeholder = ResolveConstants.back().first;
375 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000376
Chris Lattner74429932008-08-21 02:34:16 +0000377 // Loop over all users of the placeholder, updating them to reference the
378 // new value. If they reference more than one placeholder, update them all
379 // at once.
380 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000381 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000382 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000383
Chris Lattner74429932008-08-21 02:34:16 +0000384 // If the using object isn't uniqued, just update the operands. This
385 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000386 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000387 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000388 continue;
389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000390
Chris Lattner74429932008-08-21 02:34:16 +0000391 // Otherwise, we have a constant that uses the placeholder. Replace that
392 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000393 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000394 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
395 I != E; ++I) {
396 Value *NewOp;
397 if (!isa<ConstantPlaceHolder>(*I)) {
398 // Not a placeholder reference.
399 NewOp = *I;
400 } else if (*I == Placeholder) {
401 // Common case is that it just references this one placeholder.
402 NewOp = RealVal;
403 } else {
404 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000405 ResolveConstantsTy::iterator It =
406 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000407 std::pair<Constant*, unsigned>(cast<Constant>(*I),
408 0));
409 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000410 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000411 }
412
413 NewOps.push_back(cast<Constant>(NewOp));
414 }
415
416 // Make the new constant.
417 Constant *NewC;
418 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000419 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000420 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000421 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000422 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000423 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000424 } else {
425 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000426 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000427 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000428
Chris Lattner74429932008-08-21 02:34:16 +0000429 UserC->replaceAllUsesWith(NewC);
430 UserC->destroyConstant();
431 NewOps.clear();
432 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000433
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000434 // Update all ValueHandles, they should be the only users at this point.
435 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000436 delete Placeholder;
437 }
438}
439
Devang Patel05eb6172009-08-04 06:00:18 +0000440void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
441 if (Idx == size()) {
442 push_back(V);
443 return;
444 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000445
Devang Patel05eb6172009-08-04 06:00:18 +0000446 if (Idx >= size())
447 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000448
Devang Patel05eb6172009-08-04 06:00:18 +0000449 WeakVH &OldV = MDValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000450 if (!OldV) {
Devang Patel05eb6172009-08-04 06:00:18 +0000451 OldV = V;
452 return;
453 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000454
Devang Patel05eb6172009-08-04 06:00:18 +0000455 // If there was a forward reference to this value, replace it.
Dan Gohman16a5d982010-08-20 22:02:26 +0000456 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Patel05eb6172009-08-04 06:00:18 +0000457 OldV->replaceAllUsesWith(V);
Dan Gohman16a5d982010-08-20 22:02:26 +0000458 MDNode::deleteTemporary(PrevVal);
Devang Patel116b4a02009-09-03 01:38:02 +0000459 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
460 // value for Idx.
461 MDValuePtrs[Idx] = V;
Devang Patel05eb6172009-08-04 06:00:18 +0000462}
463
464Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
465 if (Idx >= size())
466 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000467
Devang Patel05eb6172009-08-04 06:00:18 +0000468 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnerfdd87902009-10-05 05:54:46 +0000469 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Patel05eb6172009-08-04 06:00:18 +0000470 return V;
471 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000472
Devang Patel05eb6172009-08-04 06:00:18 +0000473 // Create and return a placeholder, which will later be RAUW'd.
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000474 Value *V = MDNode::getTemporary(Context, None);
Devang Patel05eb6172009-08-04 06:00:18 +0000475 MDValuePtrs[Idx] = V;
476 return V;
477}
Chris Lattner1314b992007-04-22 06:23:29 +0000478
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000479Type *BitcodeReader::getTypeByID(unsigned ID) {
480 // The type table size is always specified correctly.
481 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +0000482 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +0000483
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000484 if (Type *Ty = TypeList[ID])
485 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000486
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000487 // If we have a forward reference, the only possible case is when it is to a
488 // named struct. Just create a placeholder for now.
Chris Lattner335d3992011-08-12 18:06:37 +0000489 return TypeList[ID] = StructType::create(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000490}
491
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000492
Chris Lattnerfee5a372007-05-04 03:30:17 +0000493//===----------------------------------------------------------------------===//
494// Functions for parsing blocks from the bitcode file
495//===----------------------------------------------------------------------===//
496
Bill Wendling56aeccc2013-02-04 23:32:23 +0000497
498/// \brief This fills an AttrBuilder object with the LLVM attributes that have
499/// been decoded from the given integer. This function must stay in sync with
500/// 'encodeLLVMAttributesForBitcode'.
501static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
502 uint64_t EncodedAttrs) {
503 // FIXME: Remove in 4.0.
504
505 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
506 // the bits above 31 down by 11 bits.
507 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
508 assert((!Alignment || isPowerOf2_32(Alignment)) &&
509 "Alignment must be a power of two.");
510
511 if (Alignment)
512 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +0000513 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +0000514 (EncodedAttrs & 0xffff));
515}
516
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000517std::error_code BitcodeReader::ParseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +0000518 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000519 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000520
Devang Patela05633e2008-09-26 22:53:05 +0000521 if (!MAttributes.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000522 return Error(BitcodeError::InvalidMultipleBlocks);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000523
Chris Lattnerfee5a372007-05-04 03:30:17 +0000524 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000525
Bill Wendling71173cb2013-01-27 00:36:48 +0000526 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000527
Chris Lattnerfee5a372007-05-04 03:30:17 +0000528 // Read all the records.
529 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000530 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000531
Chris Lattner27d38752013-01-20 02:13:19 +0000532 switch (Entry.Kind) {
533 case BitstreamEntry::SubBlock: // Handled for us already.
534 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000535 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +0000536 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000537 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000538 case BitstreamEntry::Record:
539 // The interesting case.
540 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +0000541 }
Joe Abbey97b7a172013-02-06 22:14:06 +0000542
Chris Lattnerfee5a372007-05-04 03:30:17 +0000543 // Read a record.
544 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +0000545 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +0000546 default: // Default behavior: ignore.
547 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000548 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
549 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +0000550 if (Record.size() & 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000551 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfee5a372007-05-04 03:30:17 +0000552
Chris Lattnerfee5a372007-05-04 03:30:17 +0000553 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +0000554 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000555 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +0000556 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +0000557 }
Devang Patela05633e2008-09-26 22:53:05 +0000558
Bill Wendlinge94d8432012-12-07 23:16:57 +0000559 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +0000560 Attrs.clear();
561 break;
562 }
Bill Wendling0dc08912013-02-12 08:13:50 +0000563 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
564 for (unsigned i = 0, e = Record.size(); i != e; ++i)
565 Attrs.push_back(MAttributeGroups[Record[i]]);
566
567 MAttributes.push_back(AttributeSet::get(Context, Attrs));
568 Attrs.clear();
569 break;
570 }
Duncan Sands04eb67e2007-11-20 14:09:29 +0000571 }
Chris Lattnerfee5a372007-05-04 03:30:17 +0000572 }
573}
574
Reid Klecknere9f36af2013-11-12 01:31:00 +0000575// Returns Attribute::None on unrecognized codes.
576static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
577 switch (Code) {
578 default:
579 return Attribute::None;
580 case bitc::ATTR_KIND_ALIGNMENT:
581 return Attribute::Alignment;
582 case bitc::ATTR_KIND_ALWAYS_INLINE:
583 return Attribute::AlwaysInline;
584 case bitc::ATTR_KIND_BUILTIN:
585 return Attribute::Builtin;
586 case bitc::ATTR_KIND_BY_VAL:
587 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +0000588 case bitc::ATTR_KIND_IN_ALLOCA:
589 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000590 case bitc::ATTR_KIND_COLD:
591 return Attribute::Cold;
592 case bitc::ATTR_KIND_INLINE_HINT:
593 return Attribute::InlineHint;
594 case bitc::ATTR_KIND_IN_REG:
595 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000596 case bitc::ATTR_KIND_JUMP_TABLE:
597 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000598 case bitc::ATTR_KIND_MIN_SIZE:
599 return Attribute::MinSize;
600 case bitc::ATTR_KIND_NAKED:
601 return Attribute::Naked;
602 case bitc::ATTR_KIND_NEST:
603 return Attribute::Nest;
604 case bitc::ATTR_KIND_NO_ALIAS:
605 return Attribute::NoAlias;
606 case bitc::ATTR_KIND_NO_BUILTIN:
607 return Attribute::NoBuiltin;
608 case bitc::ATTR_KIND_NO_CAPTURE:
609 return Attribute::NoCapture;
610 case bitc::ATTR_KIND_NO_DUPLICATE:
611 return Attribute::NoDuplicate;
612 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
613 return Attribute::NoImplicitFloat;
614 case bitc::ATTR_KIND_NO_INLINE:
615 return Attribute::NoInline;
616 case bitc::ATTR_KIND_NON_LAZY_BIND:
617 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000618 case bitc::ATTR_KIND_NON_NULL:
619 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000620 case bitc::ATTR_KIND_DEREFERENCEABLE:
621 return Attribute::Dereferenceable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000622 case bitc::ATTR_KIND_NO_RED_ZONE:
623 return Attribute::NoRedZone;
624 case bitc::ATTR_KIND_NO_RETURN:
625 return Attribute::NoReturn;
626 case bitc::ATTR_KIND_NO_UNWIND:
627 return Attribute::NoUnwind;
628 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
629 return Attribute::OptimizeForSize;
630 case bitc::ATTR_KIND_OPTIMIZE_NONE:
631 return Attribute::OptimizeNone;
632 case bitc::ATTR_KIND_READ_NONE:
633 return Attribute::ReadNone;
634 case bitc::ATTR_KIND_READ_ONLY:
635 return Attribute::ReadOnly;
636 case bitc::ATTR_KIND_RETURNED:
637 return Attribute::Returned;
638 case bitc::ATTR_KIND_RETURNS_TWICE:
639 return Attribute::ReturnsTwice;
640 case bitc::ATTR_KIND_S_EXT:
641 return Attribute::SExt;
642 case bitc::ATTR_KIND_STACK_ALIGNMENT:
643 return Attribute::StackAlignment;
644 case bitc::ATTR_KIND_STACK_PROTECT:
645 return Attribute::StackProtect;
646 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
647 return Attribute::StackProtectReq;
648 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
649 return Attribute::StackProtectStrong;
650 case bitc::ATTR_KIND_STRUCT_RET:
651 return Attribute::StructRet;
652 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
653 return Attribute::SanitizeAddress;
654 case bitc::ATTR_KIND_SANITIZE_THREAD:
655 return Attribute::SanitizeThread;
656 case bitc::ATTR_KIND_SANITIZE_MEMORY:
657 return Attribute::SanitizeMemory;
658 case bitc::ATTR_KIND_UW_TABLE:
659 return Attribute::UWTable;
660 case bitc::ATTR_KIND_Z_EXT:
661 return Attribute::ZExt;
662 }
663}
664
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000665std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
666 Attribute::AttrKind *Kind) {
Reid Klecknere9f36af2013-11-12 01:31:00 +0000667 *Kind = GetAttrFromCode(Code);
668 if (*Kind == Attribute::None)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000669 return Error(BitcodeError::InvalidValue);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000670 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000671}
672
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000673std::error_code BitcodeReader::ParseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +0000674 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000675 return Error(BitcodeError::InvalidRecord);
Bill Wendlingba629332013-02-10 23:24:25 +0000676
677 if (!MAttributeGroups.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000678 return Error(BitcodeError::InvalidMultipleBlocks);
Bill Wendlingba629332013-02-10 23:24:25 +0000679
680 SmallVector<uint64_t, 64> Record;
681
682 // Read all the records.
683 while (1) {
684 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
685
686 switch (Entry.Kind) {
687 case BitstreamEntry::SubBlock: // Handled for us already.
688 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000689 return Error(BitcodeError::MalformedBlock);
Bill Wendlingba629332013-02-10 23:24:25 +0000690 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000691 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +0000692 case BitstreamEntry::Record:
693 // The interesting case.
694 break;
695 }
696
697 // Read a record.
698 Record.clear();
699 switch (Stream.readRecord(Entry.ID, Record)) {
700 default: // Default behavior: ignore.
701 break;
702 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
703 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000704 return Error(BitcodeError::InvalidRecord);
Bill Wendlingba629332013-02-10 23:24:25 +0000705
Bill Wendlinge46707e2013-02-11 22:32:29 +0000706 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +0000707 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
708
709 AttrBuilder B;
710 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
711 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000712 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000713 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000714 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000715
716 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +0000717 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000718 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000719 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000720 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000721 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000722 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000723 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000724 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000725 else if (Kind == Attribute::Dereferenceable)
726 B.addDereferenceableAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +0000727 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +0000728 assert((Record[i] == 3 || Record[i] == 4) &&
729 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +0000730 bool HasValue = (Record[i++] == 4);
731 SmallString<64> KindStr;
732 SmallString<64> ValStr;
733
734 while (Record[i] != 0 && i != e)
735 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000736 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000737
738 if (HasValue) {
739 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +0000740 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +0000741 while (Record[i] != 0 && i != e)
742 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000743 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000744 }
745
746 B.addAttribute(KindStr.str(), ValStr.str());
747 }
748 }
749
Bill Wendlinge46707e2013-02-11 22:32:29 +0000750 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +0000751 break;
752 }
753 }
754 }
755}
756
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000757std::error_code BitcodeReader::ParseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000758 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000759 return Error(BitcodeError::InvalidRecord);
Derek Schuff206dddd2012-02-06 19:03:04 +0000760
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000761 return ParseTypeTableBody();
762}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000763
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000764std::error_code BitcodeReader::ParseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +0000765 if (!TypeList.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000766 return Error(BitcodeError::InvalidMultipleBlocks);
Chris Lattner1314b992007-04-22 06:23:29 +0000767
768 SmallVector<uint64_t, 64> Record;
769 unsigned NumRecords = 0;
770
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000771 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +0000772
Chris Lattner1314b992007-04-22 06:23:29 +0000773 // Read all the records for this type table.
774 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000775 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000776
Chris Lattner27d38752013-01-20 02:13:19 +0000777 switch (Entry.Kind) {
778 case BitstreamEntry::SubBlock: // Handled for us already.
779 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000780 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +0000781 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +0000782 if (NumRecords != TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000783 return Error(BitcodeError::MalformedBlock);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000784 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000785 case BitstreamEntry::Record:
786 // The interesting case.
787 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000788 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000789
Chris Lattner1314b992007-04-22 06:23:29 +0000790 // Read a record.
791 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +0000792 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +0000793 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +0000794 default:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000795 return Error(BitcodeError::InvalidValue);
Chris Lattner1314b992007-04-22 06:23:29 +0000796 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
797 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
798 // type list. This allows us to reserve space.
799 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000800 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000801 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000802 continue;
Chris Lattner1314b992007-04-22 06:23:29 +0000803 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +0000804 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000805 break;
Dan Gohman518cda42011-12-17 00:04:22 +0000806 case bitc::TYPE_CODE_HALF: // HALF
807 ResultTy = Type::getHalfTy(Context);
808 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000809 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +0000810 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000811 break;
812 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +0000813 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000814 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000815 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +0000816 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000817 break;
818 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000819 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000820 break;
821 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000822 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000823 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000824 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +0000825 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000826 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000827 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +0000828 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000829 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +0000830 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
831 ResultTy = Type::getX86_MMXTy(Context);
832 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000833 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
834 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000835 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000836
Owen Anderson55f1c092009-08-13 21:58:54 +0000837 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000838 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000839 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000840 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +0000841 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000842 return Error(BitcodeError::InvalidRecord);
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000843 unsigned AddressSpace = 0;
844 if (Record.size() == 2)
845 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000846 ResultTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000847 if (!ResultTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000848 return Error(BitcodeError::InvalidType);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000849 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +0000850 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000851 }
Nuno Lopes561dae02012-05-23 15:19:39 +0000852 case bitc::TYPE_CODE_FUNCTION_OLD: {
853 // FIXME: attrid is dead, remove it in LLVM 4.0
854 // FUNCTION: [vararg, attrid, retty, paramty x N]
855 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000856 return Error(BitcodeError::InvalidRecord);
Nuno Lopes561dae02012-05-23 15:19:39 +0000857 SmallVector<Type*, 8> ArgTys;
858 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
859 if (Type *T = getTypeByID(Record[i]))
860 ArgTys.push_back(T);
861 else
862 break;
863 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000864
Nuno Lopes561dae02012-05-23 15:19:39 +0000865 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000866 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000867 return Error(BitcodeError::InvalidType);
Nuno Lopes561dae02012-05-23 15:19:39 +0000868
869 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
870 break;
871 }
Chad Rosier95898722011-11-03 00:14:01 +0000872 case bitc::TYPE_CODE_FUNCTION: {
873 // FUNCTION: [vararg, retty, paramty x N]
874 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000875 return Error(BitcodeError::InvalidRecord);
Chris Lattnercc3aaf12012-01-27 03:15:49 +0000876 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +0000877 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
878 if (Type *T = getTypeByID(Record[i]))
879 ArgTys.push_back(T);
880 else
881 break;
882 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000883
Chad Rosier95898722011-11-03 00:14:01 +0000884 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000885 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000886 return Error(BitcodeError::InvalidType);
Chad Rosier95898722011-11-03 00:14:01 +0000887
888 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
889 break;
890 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000891 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +0000892 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000893 return Error(BitcodeError::InvalidRecord);
Chris Lattnercc3aaf12012-01-27 03:15:49 +0000894 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000895 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
896 if (Type *T = getTypeByID(Record[i]))
897 EltTys.push_back(T);
898 else
899 break;
900 }
901 if (EltTys.size() != Record.size()-1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000902 return Error(BitcodeError::InvalidType);
Owen Anderson03cb69f2009-08-05 23:16:16 +0000903 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000904 break;
905 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000906 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
907 if (ConvertToString(Record, 0, TypeName))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000908 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000909 continue;
910
911 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
912 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000913 return Error(BitcodeError::InvalidRecord);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000914
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000915 if (NumRecords >= TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000916 return Error(BitcodeError::InvalidTYPETable);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000917
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000918 // Check to see if this was forward referenced, if so fill in the temp.
919 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
920 if (Res) {
921 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +0000922 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000923 } else // Otherwise, create a new struct.
Chris Lattner335d3992011-08-12 18:06:37 +0000924 Res = StructType::create(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000925 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000926
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000927 SmallVector<Type*, 8> EltTys;
928 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
929 if (Type *T = getTypeByID(Record[i]))
930 EltTys.push_back(T);
931 else
932 break;
933 }
934 if (EltTys.size() != Record.size()-1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000935 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000936 Res->setBody(EltTys, Record[0]);
937 ResultTy = Res;
938 break;
939 }
940 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
941 if (Record.size() != 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000942 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000943
944 if (NumRecords >= TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000945 return Error(BitcodeError::InvalidTYPETable);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000946
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000947 // Check to see if this was forward referenced, if so fill in the temp.
948 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
949 if (Res) {
950 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +0000951 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000952 } else // Otherwise, create a new struct with no body.
Chris Lattner335d3992011-08-12 18:06:37 +0000953 Res = StructType::create(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000954 TypeName.clear();
955 ResultTy = Res;
956 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000957 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000958 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
959 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000960 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000961 if ((ResultTy = getTypeByID(Record[1])))
962 ResultTy = ArrayType::get(ResultTy, Record[0]);
963 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000964 return Error(BitcodeError::InvalidType);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000965 break;
966 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
967 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000968 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000969 if ((ResultTy = getTypeByID(Record[1])))
970 ResultTy = VectorType::get(ResultTy, Record[0]);
971 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000972 return Error(BitcodeError::InvalidType);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000973 break;
974 }
975
976 if (NumRecords >= TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000977 return Error(BitcodeError::InvalidTYPETable);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000978 assert(ResultTy && "Didn't read a type?");
Craig Topper2617dcc2014-04-15 06:32:26 +0000979 assert(!TypeList[NumRecords] && "Already read type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000980 TypeList[NumRecords++] = ResultTy;
981 }
982}
983
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000984std::error_code BitcodeReader::ParseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +0000985 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000986 return Error(BitcodeError::InvalidRecord);
Chris Lattnerccaa4482007-04-23 21:26:05 +0000987
988 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000989
Chris Lattnerccaa4482007-04-23 21:26:05 +0000990 // Read all the records for this value table.
991 SmallString<128> ValueName;
992 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000993 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000994
Chris Lattner27d38752013-01-20 02:13:19 +0000995 switch (Entry.Kind) {
996 case BitstreamEntry::SubBlock: // Handled for us already.
997 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000998 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +0000999 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001000 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001001 case BitstreamEntry::Record:
1002 // The interesting case.
1003 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001004 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001005
Chris Lattnerccaa4482007-04-23 21:26:05 +00001006 // Read a record.
1007 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001008 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001009 default: // Default behavior: unknown type.
1010 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001011 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattnerccaa4482007-04-23 21:26:05 +00001012 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001013 return Error(BitcodeError::InvalidRecord);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001014 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001015 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001016 return Error(BitcodeError::InvalidRecord);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001017 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001018
Daniel Dunbard786b512009-07-26 00:34:27 +00001019 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnerccaa4482007-04-23 21:26:05 +00001020 ValueName.clear();
1021 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001022 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001023 case bitc::VST_CODE_BBENTRY: {
Chris Lattner6be58c62007-05-03 22:18:21 +00001024 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001025 return Error(BitcodeError::InvalidRecord);
Chris Lattner6be58c62007-05-03 22:18:21 +00001026 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001027 if (!BB)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001028 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
Daniel Dunbard786b512009-07-26 00:34:27 +00001030 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001031 ValueName.clear();
1032 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001033 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001034 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001035 }
1036}
1037
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001038std::error_code BitcodeReader::ParseMetadata() {
Devang Patel89923232010-01-11 18:52:33 +00001039 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001040
1041 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001042 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001043
Devang Patel7428d8a2009-07-22 17:43:22 +00001044 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Devang Patel7428d8a2009-07-22 17:43:22 +00001046 // Read all the records.
1047 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001048 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001049
Chris Lattner27d38752013-01-20 02:13:19 +00001050 switch (Entry.Kind) {
1051 case BitstreamEntry::SubBlock: // Handled for us already.
1052 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001053 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001054 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001055 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001056 case BitstreamEntry::Record:
1057 // The interesting case.
1058 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001059 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001060
Victor Hernandezb8fd1522010-01-10 07:14:18 +00001061 bool IsFunctionLocal = false;
Devang Patel7428d8a2009-07-22 17:43:22 +00001062 // Read a record.
1063 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001064 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001065 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001066 default: // Default behavior: ignore.
1067 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001068 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001069 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001070 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001071 Record.clear();
1072 Code = Stream.ReadCode();
1073
Chris Lattnerb8778552011-06-17 17:50:30 +00001074 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner27d38752013-01-20 02:13:19 +00001075 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattnerb8778552011-06-17 17:50:30 +00001076 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patel27c87ff2009-07-29 22:34:41 +00001077
1078 // Read named metadata elements.
1079 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001080 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001081 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001082 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001083 if (!MD)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001084 return Error(BitcodeError::InvalidRecord);
Dan Gohman2637cc12010-07-21 23:38:33 +00001085 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001086 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001087 break;
1088 }
Chris Lattnerb8778552011-06-17 17:50:30 +00001089 case bitc::METADATA_FN_NODE:
Victor Hernandezb8fd1522010-01-10 07:14:18 +00001090 IsFunctionLocal = true;
1091 // fall-through
Chris Lattnerb8778552011-06-17 17:50:30 +00001092 case bitc::METADATA_NODE: {
Dan Gohman1e0213a2010-07-13 19:33:27 +00001093 if (Record.size() % 2 == 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001094 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001095
Devang Patele059ba6e2009-07-23 01:07:34 +00001096 unsigned Size = Record.size();
1097 SmallVector<Value*, 8> Elts;
1098 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001099 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001100 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001101 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfdd87902009-10-05 05:54:46 +00001102 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001103 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001104 else if (!Ty->isVoidTy())
Devang Patele059ba6e2009-07-23 01:07:34 +00001105 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1106 else
Craig Topper2617dcc2014-04-15 06:32:26 +00001107 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001108 }
Jay Foad5514afe2011-04-21 19:59:31 +00001109 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandezb8fd1522010-01-10 07:14:18 +00001110 IsFunctionLocal = false;
Devang Patel89923232010-01-11 18:52:33 +00001111 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001112 break;
1113 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001114 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00001115 std::string String(Record.begin(), Record.end());
1116 llvm::UpgradeMDStringConstant(String);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001117 Value *V = MDString::get(Context, String);
Devang Patel89923232010-01-11 18:52:33 +00001118 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00001119 break;
1120 }
Devang Patelaf206b82009-09-18 19:26:43 +00001121 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001122 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001123 return Error(BitcodeError::InvalidRecord);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001124
Devang Patelb1a44772009-09-28 21:14:55 +00001125 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001126 SmallString<8> Name(Record.begin()+1, Record.end());
1127
Chris Lattnera0566972009-12-29 09:01:33 +00001128 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00001129 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001130 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
Devang Patelaf206b82009-09-18 19:26:43 +00001131 break;
1132 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001133 }
1134 }
1135}
1136
Jan Wen Voungafaced02012-10-11 20:20:40 +00001137/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner08feb1e2007-04-24 04:04:35 +00001138/// the LSB for dense VBR encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001139uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001140 if ((V & 1) == 0)
1141 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001142 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001143 return -(V >> 1);
1144 // There is no such thing as -0 with integers. "-0" really means MININT.
1145 return 1ULL << 63;
1146}
1147
Chris Lattner44c17072007-04-26 02:46:40 +00001148/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1149/// values and aliases that we can.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001150std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00001151 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1152 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001153 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001154
Chris Lattner44c17072007-04-26 02:46:40 +00001155 GlobalInitWorklist.swap(GlobalInits);
1156 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001157 FunctionPrefixWorklist.swap(FunctionPrefixes);
Chris Lattner44c17072007-04-26 02:46:40 +00001158
1159 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00001160 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001161 if (ValID >= ValueList.size()) {
1162 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00001163 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001164 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001165 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00001166 GlobalInitWorklist.back().first->setInitializer(C);
1167 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001168 return Error(BitcodeError::ExpectedConstant);
Chris Lattner44c17072007-04-26 02:46:40 +00001169 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001170 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001171 }
1172
1173 while (!AliasInitWorklist.empty()) {
1174 unsigned ValID = AliasInitWorklist.back().second;
1175 if (ValID >= ValueList.size()) {
1176 AliasInits.push_back(AliasInitWorklist.back());
1177 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001178 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Rafael Espindola64c1e182014-06-03 02:41:57 +00001179 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00001180 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001181 return Error(BitcodeError::ExpectedConstant);
Chris Lattner44c17072007-04-26 02:46:40 +00001182 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001183 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001184 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001185
1186 while (!FunctionPrefixWorklist.empty()) {
1187 unsigned ValID = FunctionPrefixWorklist.back().second;
1188 if (ValID >= ValueList.size()) {
1189 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1190 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001191 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001192 FunctionPrefixWorklist.back().first->setPrefixData(C);
1193 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001194 return Error(BitcodeError::ExpectedConstant);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001195 }
1196 FunctionPrefixWorklist.pop_back();
1197 }
1198
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001199 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00001200}
1201
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001202static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1203 SmallVector<uint64_t, 8> Words(Vals.size());
1204 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00001205 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001206
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001207 return APInt(TypeBits, Words);
1208}
1209
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001210std::error_code BitcodeReader::ParseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001211 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001212 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001213
1214 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001215
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001216 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00001217 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00001218 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001219 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001220 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001221
Chris Lattner27d38752013-01-20 02:13:19 +00001222 switch (Entry.Kind) {
1223 case BitstreamEntry::SubBlock: // Handled for us already.
1224 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001225 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001226 case BitstreamEntry::EndBlock:
1227 if (NextCstNo != ValueList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001228 return Error(BitcodeError::InvalidConstantReference);
Joe Abbey97b7a172013-02-06 22:14:06 +00001229
Chris Lattner27d38752013-01-20 02:13:19 +00001230 // Once all the constants have been read, go through and resolve forward
1231 // references.
1232 ValueList.ResolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001233 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001234 case BitstreamEntry::Record:
1235 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00001236 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001237 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001238
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001239 // Read a record.
1240 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001241 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001242 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00001243 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001244 default: // Default behavior: unknown constant
1245 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00001246 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001247 break;
1248 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1249 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001250 return Error(BitcodeError::InvalidRecord);
Karthik Bhat82540e92014-03-27 12:08:23 +00001251 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001252 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001253 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00001254 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001255 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00001256 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001257 break;
1258 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001259 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001260 return Error(BitcodeError::InvalidRecord);
Jan Wen Voungafaced02012-10-11 20:20:40 +00001261 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00001262 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001263 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001264 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001265 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001266
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001267 APInt VInt = ReadWideAPInt(Record,
1268 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001269 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001270
Chris Lattner08feb1e2007-04-24 04:04:35 +00001271 break;
1272 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00001273 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00001274 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001275 return Error(BitcodeError::InvalidRecord);
Dan Gohman518cda42011-12-17 00:04:22 +00001276 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00001277 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1278 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00001279 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00001280 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1281 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001282 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00001283 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1284 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001285 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00001286 // Bits are not stored the same way as a normal i80 APInt, compensate.
1287 uint64_t Rearrange[2];
1288 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1289 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00001290 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1291 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001292 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001293 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1294 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001295 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001296 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1297 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001298 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001299 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001300 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00001301 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001302
Chris Lattnere14cb882007-05-04 19:11:41 +00001303 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1304 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001305 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001306
Chris Lattnere14cb882007-05-04 19:11:41 +00001307 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001308 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001309
Chris Lattner229907c2011-07-18 04:54:35 +00001310 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00001311 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001312 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00001313 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00001314 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001315 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1316 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001317 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001318 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00001319 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001320 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1321 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001322 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001323 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00001324 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00001325 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001326 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00001327 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001328 break;
1329 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001330 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00001331 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1332 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001333 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001334
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001335 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001336 V = ConstantDataArray::getString(Context, Elts,
1337 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00001338 break;
1339 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00001340 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1341 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001342 return Error(BitcodeError::InvalidRecord);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001343
Chris Lattner372dd1e2012-01-30 00:51:16 +00001344 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1345 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001346
Chris Lattner372dd1e2012-01-30 00:51:16 +00001347 if (EltTy->isIntegerTy(8)) {
1348 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1349 if (isa<VectorType>(CurTy))
1350 V = ConstantDataVector::get(Context, Elts);
1351 else
1352 V = ConstantDataArray::get(Context, Elts);
1353 } else if (EltTy->isIntegerTy(16)) {
1354 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1355 if (isa<VectorType>(CurTy))
1356 V = ConstantDataVector::get(Context, Elts);
1357 else
1358 V = ConstantDataArray::get(Context, Elts);
1359 } else if (EltTy->isIntegerTy(32)) {
1360 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1361 if (isa<VectorType>(CurTy))
1362 V = ConstantDataVector::get(Context, Elts);
1363 else
1364 V = ConstantDataArray::get(Context, Elts);
1365 } else if (EltTy->isIntegerTy(64)) {
1366 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1367 if (isa<VectorType>(CurTy))
1368 V = ConstantDataVector::get(Context, Elts);
1369 else
1370 V = ConstantDataArray::get(Context, Elts);
1371 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001372 SmallVector<float, 16> Elts(Size);
1373 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001374 if (isa<VectorType>(CurTy))
1375 V = ConstantDataVector::get(Context, Elts);
1376 else
1377 V = ConstantDataArray::get(Context, Elts);
1378 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001379 SmallVector<double, 16> Elts(Size);
1380 std::transform(Record.begin(), Record.end(), Elts.begin(),
1381 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001382 if (isa<VectorType>(CurTy))
1383 V = ConstantDataVector::get(Context, Elts);
1384 else
1385 V = ConstantDataArray::get(Context, Elts);
1386 } else {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001387 return Error(BitcodeError::InvalidTypeForValue);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001388 }
1389 break;
1390 }
1391
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001392 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001393 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001394 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001395 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001396 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001397 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00001398 } else {
1399 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1400 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00001401 unsigned Flags = 0;
1402 if (Record.size() >= 4) {
1403 if (Opc == Instruction::Add ||
1404 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001405 Opc == Instruction::Mul ||
1406 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00001407 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1408 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1409 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1410 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00001411 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001412 Opc == Instruction::UDiv ||
1413 Opc == Instruction::LShr ||
1414 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00001415 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00001416 Flags |= SDivOperator::IsExact;
1417 }
1418 }
1419 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00001420 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001421 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001422 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001423 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001424 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001425 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001426 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00001427 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001428 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00001429 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00001430 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001431 if (!OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001432 return Error(BitcodeError::InvalidRecord);
Chris Lattner890683d2007-04-24 18:15:21 +00001433 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001434 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1435 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001436 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001437 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001438 }
Dan Gohman1639c392009-07-27 21:53:46 +00001439 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001440 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001441 if (Record.size() & 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001442 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001443 SmallVector<Constant*, 16> Elts;
Chris Lattnere14cb882007-05-04 19:11:41 +00001444 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001445 Type *ElTy = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001446 if (!ElTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001447 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001448 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1449 }
Jay Foaded8db7d2011-07-21 14:31:17 +00001450 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad2f5fc8c2011-07-21 15:15:37 +00001451 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1452 BitCode ==
1453 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00001454 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001455 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00001456 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001457 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001458 return Error(BitcodeError::InvalidRecord);
Joe Abbey1a6e7702013-09-12 22:02:31 +00001459
1460 Type *SelectorTy = Type::getInt1Ty(Context);
1461
1462 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1463 // vector. Otherwise, it must be a single bit.
1464 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1465 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1466 VTy->getNumElements());
1467
1468 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1469 SelectorTy),
1470 ValueList.getConstantFwdRef(Record[1],CurTy),
1471 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001472 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00001473 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001474 case bitc::CST_CODE_CE_EXTRACTELT
1475 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001476 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001477 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00001478 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001479 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001480 if (!OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001481 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001482 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001483 Constant *Op1 = nullptr;
1484 if (Record.size() == 4) {
1485 Type *IdxTy = getTypeByID(Record[2]);
1486 if (!IdxTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001487 return Error(BitcodeError::InvalidRecord);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001488 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1489 } else // TODO: Remove with llvm 4.0
1490 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1491 if (!Op1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001492 return Error(BitcodeError::InvalidRecord);
Owen Anderson487375e2009-07-29 18:55:55 +00001493 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001494 break;
1495 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001496 case bitc::CST_CODE_CE_INSERTELT
1497 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001498 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00001499 if (Record.size() < 3 || !OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001500 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001501 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1502 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1503 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001504 Constant *Op2 = nullptr;
1505 if (Record.size() == 4) {
1506 Type *IdxTy = getTypeByID(Record[2]);
1507 if (!IdxTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001508 return Error(BitcodeError::InvalidRecord);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001509 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1510 } else // TODO: Remove with llvm 4.0
1511 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1512 if (!Op2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001513 return Error(BitcodeError::InvalidRecord);
Owen Anderson487375e2009-07-29 18:55:55 +00001514 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001515 break;
1516 }
1517 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001518 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00001519 if (Record.size() < 3 || !OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001520 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001521 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1522 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001523 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00001524 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001525 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00001526 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001527 break;
1528 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00001529 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001530 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1531 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00001532 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001533 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001534 return Error(BitcodeError::InvalidRecord);
Nate Begeman94aa38d2009-02-12 21:28:33 +00001535 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1536 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001537 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00001538 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00001539 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00001540 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00001541 break;
1542 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001543 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001544 if (Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001545 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00001546 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001547 if (!OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001548 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001549 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1550 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1551
Duncan Sands9dff9be2010-02-15 16:12:20 +00001552 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00001553 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00001554 else
Owen Anderson487375e2009-07-29 18:55:55 +00001555 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001556 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00001557 }
Chad Rosierd8c76102012-09-05 19:00:49 +00001558 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00001559 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001560 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001561 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001562 return Error(BitcodeError::InvalidRecord);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001563 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00001564 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00001565 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001566 unsigned AsmStrSize = Record[1];
1567 if (2+AsmStrSize >= Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001568 return Error(BitcodeError::InvalidRecord);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001569 unsigned ConstStrSize = Record[2+AsmStrSize];
1570 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001571 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001572
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001573 for (unsigned i = 0; i != AsmStrSize; ++i)
1574 AsmStr += (char)Record[2+i];
1575 for (unsigned i = 0; i != ConstStrSize; ++i)
1576 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00001577 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001578 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00001579 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001580 break;
1581 }
Chad Rosierd8c76102012-09-05 19:00:49 +00001582 // This version adds support for the asm dialect keywords (e.g.,
1583 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001584 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001585 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001586 return Error(BitcodeError::InvalidRecord);
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001587 std::string AsmStr, ConstrStr;
1588 bool HasSideEffects = Record[0] & 1;
1589 bool IsAlignStack = (Record[0] >> 1) & 1;
1590 unsigned AsmDialect = Record[0] >> 2;
1591 unsigned AsmStrSize = Record[1];
1592 if (2+AsmStrSize >= Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001593 return Error(BitcodeError::InvalidRecord);
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001594 unsigned ConstStrSize = Record[2+AsmStrSize];
1595 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001596 return Error(BitcodeError::InvalidRecord);
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001597
1598 for (unsigned i = 0; i != AsmStrSize; ++i)
1599 AsmStr += (char)Record[2+i];
1600 for (unsigned i = 0; i != ConstStrSize; ++i)
1601 ConstrStr += (char)Record[3+AsmStrSize+i];
1602 PointerType *PTy = cast<PointerType>(CurTy);
1603 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1604 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00001605 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001606 break;
1607 }
Chris Lattner5956dc82009-10-28 05:53:48 +00001608 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00001609 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001610 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00001611 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001612 if (!FnTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001613 return Error(BitcodeError::InvalidRecord);
Chris Lattner5956dc82009-10-28 05:53:48 +00001614 Function *Fn =
1615 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00001616 if (!Fn)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001617 return Error(BitcodeError::InvalidRecord);
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001618
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00001619 // Don't let Fn get dematerialized.
1620 BlockAddressesTaken.insert(Fn);
1621
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001622 // If the function is already parsed we can insert the block address right
1623 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001624 BasicBlock *BB;
1625 unsigned BBID = Record[2];
1626 if (!BBID)
1627 // Invalid reference to entry block.
1628 return Error(BitcodeError::InvalidID);
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001629 if (!Fn->empty()) {
1630 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001631 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001632 if (BBI == BBE)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001633 return Error(BitcodeError::InvalidID);
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001634 ++BBI;
1635 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001636 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001637 } else {
1638 // Otherwise insert a placeholder and remember it so it can be inserted
1639 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00001640 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1641 if (FwdBBs.empty())
1642 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00001643 if (FwdBBs.size() < BBID + 1)
1644 FwdBBs.resize(BBID + 1);
1645 if (!FwdBBs[BBID])
1646 FwdBBs[BBID] = BasicBlock::Create(Context);
1647 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001648 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001649 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00001650 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001651 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001653
Chris Lattner83930552007-05-01 07:01:57 +00001654 ValueList.AssignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00001655 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001656 }
1657}
Chris Lattner1314b992007-04-22 06:23:29 +00001658
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001659std::error_code BitcodeReader::ParseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00001660 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001661 return Error(BitcodeError::InvalidRecord);
Chad Rosierca2567b2011-12-07 21:44:12 +00001662
Chad Rosierca2567b2011-12-07 21:44:12 +00001663 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001664 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00001665 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001666 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001667
Chris Lattner27d38752013-01-20 02:13:19 +00001668 switch (Entry.Kind) {
1669 case BitstreamEntry::SubBlock: // Handled for us already.
1670 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001671 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001672 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001673 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001674 case BitstreamEntry::Record:
1675 // The interesting case.
1676 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00001677 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001678
Chad Rosierca2567b2011-12-07 21:44:12 +00001679 // Read a use list record.
1680 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001681 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00001682 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00001683 default: // Default behavior: unknown type.
1684 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001685 case bitc::USELIST_CODE_BB:
1686 IsBB = true;
1687 // fallthrough
1688 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00001689 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001690 if (RecordLength < 3)
1691 // Records should have at least an ID and two indexes.
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001692 return Error(BitcodeError::InvalidRecord);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001693 unsigned ID = Record.back();
1694 Record.pop_back();
1695
1696 Value *V;
1697 if (IsBB) {
1698 assert(ID < FunctionBBs.size() && "Basic block not found");
1699 V = FunctionBBs[ID];
1700 } else
1701 V = ValueList[ID];
1702 unsigned NumUses = 0;
1703 SmallDenseMap<const Use *, unsigned, 16> Order;
1704 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00001705 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001706 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00001707 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001708 }
1709 if (Order.size() != Record.size() || NumUses > Record.size())
1710 // Mismatches can happen if the functions are being materialized lazily
1711 // (out-of-order), or a value has been upgraded.
1712 break;
1713
1714 V->sortUseList([&](const Use &L, const Use &R) {
1715 return Order.lookup(&L) < Order.lookup(&R);
1716 });
Chad Rosierca2567b2011-12-07 21:44:12 +00001717 break;
1718 }
1719 }
1720 }
1721}
1722
Chris Lattner85b7b402007-05-01 05:52:21 +00001723/// RememberAndSkipFunctionBody - When we see the block for a function body,
1724/// remember where it is and then skip it. This lets us lazily deserialize the
1725/// functions.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001726std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001727 // Get the function we are talking about.
1728 if (FunctionsWithBodies.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001729 return Error(BitcodeError::InsufficientFunctionProtos);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001730
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001731 Function *Fn = FunctionsWithBodies.back();
1732 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001733
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001734 // Save the current stream state.
1735 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001736 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001737
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001738 // Skip over the function block for now.
1739 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001740 return Error(BitcodeError::InvalidRecord);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001741 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001742}
1743
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001744std::error_code BitcodeReader::GlobalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001745 // Patch the initializers for globals and aliases up.
1746 ResolveGlobalAndAliasInits();
1747 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001748 return Error(BitcodeError::MalformedGlobalInitializerSet);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001749
1750 // Look for intrinsic functions which need to be upgraded at some point
1751 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1752 FI != FE; ++FI) {
1753 Function *NewFn;
1754 if (UpgradeIntrinsicFunction(FI, NewFn))
1755 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1756 }
1757
1758 // Look for global variables which need to be renamed.
1759 for (Module::global_iterator
1760 GI = TheModule->global_begin(), GE = TheModule->global_end();
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001761 GI != GE;) {
1762 GlobalVariable *GV = GI++;
1763 UpgradeGlobalVariable(GV);
1764 }
1765
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001766 // Force deallocation of memory for these vectors to favor the client that
1767 // want lazy deserialization.
1768 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1769 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001770 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001771}
1772
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001773std::error_code BitcodeReader::ParseModule(bool Resume) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001774 if (Resume)
1775 Stream.JumpToBit(NextUnreadBit);
1776 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001777 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001778
Chris Lattner1314b992007-04-22 06:23:29 +00001779 SmallVector<uint64_t, 64> Record;
1780 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00001781 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00001782
1783 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00001784 while (1) {
1785 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00001786
Chris Lattner27d38752013-01-20 02:13:19 +00001787 switch (Entry.Kind) {
1788 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001789 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001790 case BitstreamEntry::EndBlock:
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001791 return GlobalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00001792
Chris Lattner27d38752013-01-20 02:13:19 +00001793 case BitstreamEntry::SubBlock:
1794 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00001795 default: // Skip unknown content.
1796 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001797 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001798 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00001799 case bitc::BLOCKINFO_BLOCK_ID:
1800 if (Stream.ReadBlockInfoBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001801 return Error(BitcodeError::MalformedBlock);
Chris Lattner6eeea5d2007-05-05 18:57:30 +00001802 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001803 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001804 if (std::error_code EC = ParseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001805 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001806 break;
Bill Wendlingba629332013-02-10 23:24:25 +00001807 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001808 if (std::error_code EC = ParseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001809 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00001810 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001811 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001812 if (std::error_code EC = ParseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001813 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00001814 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001815 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001816 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001817 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001818 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001819 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001820 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001821 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001822 return EC;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001823 if (std::error_code EC = ResolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001824 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001825 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001826 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001827 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001828 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00001829 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001830 case bitc::FUNCTION_BLOCK_ID:
1831 // If this is the first function body we've seen, reverse the
1832 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001833 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001834 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001835 if (std::error_code EC = GlobalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001836 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001837 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001838 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001839
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001840 if (std::error_code EC = RememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001841 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001842 // For streaming bitcode, suspend parsing when we reach the function
1843 // bodies. Subsequent materialization calls will resume it when
1844 // necessary. For streaming, the function bodies must be at the end of
1845 // the bitcode. If the bitcode file is old, the symbol table will be
1846 // at the end instead and will not have been seen yet. In this case,
1847 // just finish the parse now.
1848 if (LazyStreamer && SeenValueSymbolTable) {
1849 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001850 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001851 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001852 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00001853 case bitc::USELIST_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001854 if (std::error_code EC = ParseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001855 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00001856 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001857 }
1858 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00001859
Chris Lattner27d38752013-01-20 02:13:19 +00001860 case BitstreamEntry::Record:
1861 // The interesting case.
1862 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001863 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001864
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001865
Chris Lattner1314b992007-04-22 06:23:29 +00001866 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00001867 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00001868 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001869 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00001870 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001871 return Error(BitcodeError::InvalidRecord);
Jan Wen Voungafaced02012-10-11 20:20:40 +00001872 // Only version #0 and #1 are supported so far.
1873 unsigned module_version = Record[0];
1874 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001875 default:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001876 return Error(BitcodeError::InvalidValue);
Jan Wen Voungafaced02012-10-11 20:20:40 +00001877 case 0:
1878 UseRelativeIDs = false;
1879 break;
1880 case 1:
1881 UseRelativeIDs = true;
1882 break;
1883 }
Chris Lattner1314b992007-04-22 06:23:29 +00001884 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00001885 }
Chris Lattnere14cb882007-05-04 19:11:41 +00001886 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00001887 std::string S;
1888 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001889 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001890 TheModule->setTargetTriple(S);
1891 break;
1892 }
Chris Lattnere14cb882007-05-04 19:11:41 +00001893 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00001894 std::string S;
1895 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001896 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001897 TheModule->setDataLayout(S);
1898 break;
1899 }
Chris Lattnere14cb882007-05-04 19:11:41 +00001900 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00001901 std::string S;
1902 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001903 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001904 TheModule->setModuleInlineAsm(S);
1905 break;
1906 }
Bill Wendling706d3d62012-11-28 08:41:48 +00001907 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1908 // FIXME: Remove in 4.0.
1909 std::string S;
1910 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001911 return Error(BitcodeError::InvalidRecord);
Bill Wendling706d3d62012-11-28 08:41:48 +00001912 // Ignore value.
1913 break;
1914 }
Chris Lattnere14cb882007-05-04 19:11:41 +00001915 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00001916 std::string S;
1917 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001918 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001919 SectionTable.push_back(S);
1920 break;
1921 }
Gordon Henriksend930f912008-08-17 18:44:35 +00001922 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00001923 std::string S;
1924 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001925 return Error(BitcodeError::InvalidRecord);
Gordon Henriksend930f912008-08-17 18:44:35 +00001926 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001927 break;
1928 }
David Majnemerdad0a642014-06-27 18:19:56 +00001929 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1930 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001931 return Error(BitcodeError::InvalidRecord);
David Majnemerdad0a642014-06-27 18:19:56 +00001932 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1933 unsigned ComdatNameSize = Record[1];
1934 std::string ComdatName;
1935 ComdatName.reserve(ComdatNameSize);
1936 for (unsigned i = 0; i != ComdatNameSize; ++i)
1937 ComdatName += (char)Record[2 + i];
1938 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1939 C->setSelectionKind(SK);
1940 ComdatList.push_back(C);
1941 break;
1942 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001943 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001944 // linkage, alignment, section, visibility, threadlocal,
Nico Rieck7157bb72014-01-14 15:22:47 +00001945 // unnamed_addr, dllstorageclass]
Chris Lattner1314b992007-04-22 06:23:29 +00001946 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00001947 if (Record.size() < 6)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001948 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00001949 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001950 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001951 return Error(BitcodeError::InvalidRecord);
Duncan Sands19d0b472010-02-16 11:11:14 +00001952 if (!Ty->isPointerTy())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001953 return Error(BitcodeError::InvalidTypeForValue);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001954 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattner1314b992007-04-22 06:23:29 +00001955 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001956
Chris Lattner1314b992007-04-22 06:23:29 +00001957 bool isConstant = Record[1];
1958 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1959 unsigned Alignment = (1 << Record[4]) >> 1;
1960 std::string Section;
1961 if (Record[5]) {
1962 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001963 return Error(BitcodeError::InvalidID);
Chris Lattner1314b992007-04-22 06:23:29 +00001964 Section = SectionTable[Record[5]-1];
1965 }
Chris Lattner4b00d922007-04-23 16:04:05 +00001966 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00001967 // Local linkage must have default visibility.
1968 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1969 // FIXME: Change to an error if non-default in 4.0.
Chris Lattner53862f72007-05-06 19:27:46 +00001970 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001971
1972 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00001973 if (Record.size() > 7)
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001974 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00001975
Rafael Espindola45e6c192011-01-08 16:42:36 +00001976 bool UnnamedAddr = false;
1977 if (Record.size() > 8)
1978 UnnamedAddr = Record[8];
1979
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001980 bool ExternallyInitialized = false;
1981 if (Record.size() > 9)
1982 ExternallyInitialized = Record[9];
1983
Chris Lattner1314b992007-04-22 06:23:29 +00001984 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00001985 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00001986 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00001987 NewGV->setAlignment(Alignment);
1988 if (!Section.empty())
1989 NewGV->setSection(Section);
1990 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00001991 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001992
Nico Rieck7157bb72014-01-14 15:22:47 +00001993 if (Record.size() > 10)
1994 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1995 else
1996 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1997
Chris Lattnerccaa4482007-04-23 21:26:05 +00001998 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001999
Chris Lattner47d131b2007-04-24 00:18:21 +00002000 // Remember which value to use for the global initializer.
2001 if (unsigned InitID = Record[2])
2002 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00002003
2004 if (Record.size() > 11)
2005 if (unsigned ComdatID = Record[11]) {
2006 assert(ComdatID <= ComdatList.size());
2007 NewGV->setComdat(ComdatList[ComdatID - 1]);
2008 }
Chris Lattner1314b992007-04-22 06:23:29 +00002009 break;
2010 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002011 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00002012 // alignment, section, visibility, gc, unnamed_addr,
2013 // dllstorageclass]
Chris Lattner1314b992007-04-22 06:23:29 +00002014 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002015 if (Record.size() < 8)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002016 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002017 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002018 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002019 return Error(BitcodeError::InvalidRecord);
Duncan Sands19d0b472010-02-16 11:11:14 +00002020 if (!Ty->isPointerTy())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002021 return Error(BitcodeError::InvalidTypeForValue);
Chris Lattner229907c2011-07-18 04:54:35 +00002022 FunctionType *FTy =
Chris Lattner1314b992007-04-22 06:23:29 +00002023 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2024 if (!FTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002025 return Error(BitcodeError::InvalidTypeForValue);
Chris Lattner1314b992007-04-22 06:23:29 +00002026
Gabor Greife9ecc682008-04-06 20:25:17 +00002027 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2028 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00002029
Sandeep Patel68c5f472009-09-02 08:44:58 +00002030 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002031 bool isProto = Record[2];
Chris Lattner1314b992007-04-22 06:23:29 +00002032 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel4c758ea2008-09-25 21:00:45 +00002033 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002034
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002035 Func->setAlignment((1 << Record[5]) >> 1);
2036 if (Record[6]) {
2037 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002038 return Error(BitcodeError::InvalidID);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002039 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00002040 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002041 // Local linkage must have default visibility.
2042 if (!Func->hasLocalLinkage())
2043 // FIXME: Change to an error if non-default in 4.0.
2044 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00002045 if (Record.size() > 8 && Record[8]) {
Gordon Henriksend930f912008-08-17 18:44:35 +00002046 if (Record[8]-1 > GCTable.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002047 return Error(BitcodeError::InvalidID);
Gordon Henriksend930f912008-08-17 18:44:35 +00002048 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00002049 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00002050 bool UnnamedAddr = false;
2051 if (Record.size() > 9)
2052 UnnamedAddr = Record[9];
2053 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002054 if (Record.size() > 10 && Record[10] != 0)
2055 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00002056
2057 if (Record.size() > 11)
2058 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2059 else
2060 UpgradeDLLImportExportLinkage(Func, Record[3]);
2061
David Majnemerdad0a642014-06-27 18:19:56 +00002062 if (Record.size() > 12)
2063 if (unsigned ComdatID = Record[12]) {
2064 assert(ComdatID <= ComdatList.size());
2065 Func->setComdat(ComdatList[ComdatID - 1]);
2066 }
2067
Chris Lattnerccaa4482007-04-23 21:26:05 +00002068 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002069
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002070 // If this is a function with a body, remember the prototype we are
2071 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002072 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00002073 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002074 FunctionsWithBodies.push_back(Func);
Rafael Espindola1b47a282014-10-23 15:20:05 +00002075 if (LazyStreamer)
2076 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002077 }
Chris Lattner1314b992007-04-22 06:23:29 +00002078 break;
2079 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002080 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00002081 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00002082 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00002083 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002084 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002085 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002086 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002087 return Error(BitcodeError::InvalidRecord);
Rafael Espindolaa8004452014-05-16 14:22:33 +00002088 auto *PTy = dyn_cast<PointerType>(Ty);
2089 if (!PTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002090 return Error(BitcodeError::InvalidTypeForValue);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002091
Rafael Espindolaa8004452014-05-16 14:22:33 +00002092 auto *NewGA =
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00002093 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2094 GetDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002095 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002096 // Local linkage must have default visibility.
2097 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2098 // FIXME: Change to an error if non-default in 4.0.
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002099 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00002100 if (Record.size() > 4)
2101 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2102 else
2103 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00002104 if (Record.size() > 5)
2105 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00002106 if (Record.size() > 6)
2107 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00002108 ValueList.push_back(NewGA);
2109 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2110 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002111 }
Chris Lattner831d4202007-04-26 03:27:58 +00002112 /// MODULE_CODE_PURGEVALS: [numvals]
2113 case bitc::MODULE_CODE_PURGEVALS:
2114 // Trim down the value list to the specified size.
2115 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002116 return Error(BitcodeError::InvalidRecord);
Chris Lattner831d4202007-04-26 03:27:58 +00002117 ValueList.shrinkTo(Record[0]);
2118 break;
2119 }
Chris Lattner1314b992007-04-22 06:23:29 +00002120 Record.clear();
2121 }
Chris Lattner1314b992007-04-22 06:23:29 +00002122}
2123
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002124std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002125 TheModule = nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002126
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002127 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002128 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002129
Chris Lattner1314b992007-04-22 06:23:29 +00002130 // Sniff for the signature.
2131 if (Stream.Read(8) != 'B' ||
2132 Stream.Read(8) != 'C' ||
2133 Stream.Read(4) != 0x0 ||
2134 Stream.Read(4) != 0xC ||
2135 Stream.Read(4) != 0xE ||
2136 Stream.Read(4) != 0xD)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002137 return Error(BitcodeError::InvalidBitcodeSignature);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002138
Chris Lattner1314b992007-04-22 06:23:29 +00002139 // We expect a number of well-defined blocks, though we don't necessarily
2140 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002141 while (1) {
2142 if (Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002143 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002144
Chris Lattner27d38752013-01-20 02:13:19 +00002145 BitstreamEntry Entry =
2146 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00002147
Chris Lattner27d38752013-01-20 02:13:19 +00002148 switch (Entry.Kind) {
2149 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002150 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002151 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002152 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002153
Chris Lattner27d38752013-01-20 02:13:19 +00002154 case BitstreamEntry::SubBlock:
2155 switch (Entry.ID) {
2156 case bitc::BLOCKINFO_BLOCK_ID:
2157 if (Stream.ReadBlockInfoBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002158 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002159 break;
2160 case bitc::MODULE_BLOCK_ID:
2161 // Reject multiple MODULE_BLOCK's in a single bitstream.
2162 if (TheModule)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002163 return Error(BitcodeError::InvalidMultipleBlocks);
Chris Lattner27d38752013-01-20 02:13:19 +00002164 TheModule = M;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002165 if (std::error_code EC = ParseModule(false))
Rafael Espindola48da4f42013-11-04 16:16:24 +00002166 return EC;
2167 if (LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002168 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002169 break;
2170 default:
2171 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002172 return Error(BitcodeError::InvalidRecord);
Chris Lattner27d38752013-01-20 02:13:19 +00002173 break;
2174 }
2175 continue;
2176 case BitstreamEntry::Record:
2177 // There should be no records in the top-level of blocks.
Joe Abbey97b7a172013-02-06 22:14:06 +00002178
Chris Lattner27d38752013-01-20 02:13:19 +00002179 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosiera15e3aa2011-08-09 22:23:40 +00002180 // to the end of them. If this file size is a multiple of 4 but not 8, we
2181 // have to read and ignore these final 4 bytes :-(
Chris Lattner27d38752013-01-20 02:13:19 +00002182 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002183 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling318f03f2012-07-19 00:15:11 +00002184 Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002185 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002186
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002187 return Error(BitcodeError::InvalidRecord);
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002188 }
Chris Lattner1314b992007-04-22 06:23:29 +00002189 }
Chris Lattner1314b992007-04-22 06:23:29 +00002190}
Chris Lattner6694f602007-04-29 07:54:31 +00002191
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002192ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00002193 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002194 return Error(BitcodeError::InvalidRecord);
Bill Wendling0198ce02010-10-06 01:22:42 +00002195
2196 SmallVector<uint64_t, 64> Record;
2197
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002198 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00002199 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002200 while (1) {
2201 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002202
Chris Lattner27d38752013-01-20 02:13:19 +00002203 switch (Entry.Kind) {
2204 case BitstreamEntry::SubBlock: // Handled for us already.
2205 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002206 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002207 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00002208 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00002209 case BitstreamEntry::Record:
2210 // The interesting case.
2211 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00002212 }
2213
2214 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002215 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00002216 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00002217 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002218 std::string S;
2219 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002220 return Error(BitcodeError::InvalidRecord);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002221 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00002222 break;
2223 }
2224 }
2225 Record.clear();
2226 }
Rafael Espindolae6107792014-07-04 20:05:56 +00002227 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00002228}
2229
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002230ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002231 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002232 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00002233
2234 // Sniff for the signature.
2235 if (Stream.Read(8) != 'B' ||
2236 Stream.Read(8) != 'C' ||
2237 Stream.Read(4) != 0x0 ||
2238 Stream.Read(4) != 0xC ||
2239 Stream.Read(4) != 0xE ||
2240 Stream.Read(4) != 0xD)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002241 return Error(BitcodeError::InvalidBitcodeSignature);
Bill Wendling0198ce02010-10-06 01:22:42 +00002242
2243 // We expect a number of well-defined blocks, though we don't necessarily
2244 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002245 while (1) {
2246 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002247
Chris Lattner27d38752013-01-20 02:13:19 +00002248 switch (Entry.Kind) {
2249 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002250 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002251 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002252 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002253
Chris Lattner27d38752013-01-20 02:13:19 +00002254 case BitstreamEntry::SubBlock:
2255 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00002256 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00002257
Chris Lattner27d38752013-01-20 02:13:19 +00002258 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00002259 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002260 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002261 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002262
Chris Lattner27d38752013-01-20 02:13:19 +00002263 case BitstreamEntry::Record:
2264 Stream.skipRecord(Entry.ID);
2265 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00002266 }
2267 }
Bill Wendling0198ce02010-10-06 01:22:42 +00002268}
2269
Devang Patelaf206b82009-09-18 19:26:43 +00002270/// ParseMetadataAttachment - Parse metadata attachments.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002271std::error_code BitcodeReader::ParseMetadataAttachment() {
Devang Patelaf206b82009-09-18 19:26:43 +00002272 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002273 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002274
Devang Patelaf206b82009-09-18 19:26:43 +00002275 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00002276 while (1) {
2277 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002278
Chris Lattner27d38752013-01-20 02:13:19 +00002279 switch (Entry.Kind) {
2280 case BitstreamEntry::SubBlock: // Handled for us already.
2281 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002282 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002283 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002284 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002285 case BitstreamEntry::Record:
2286 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00002287 break;
2288 }
Chris Lattner27d38752013-01-20 02:13:19 +00002289
Devang Patelaf206b82009-09-18 19:26:43 +00002290 // Read a metadata attachment record.
2291 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00002292 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00002293 default: // Default behavior: ignore.
2294 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00002295 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00002296 unsigned RecordLength = Record.size();
2297 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002298 return Error(BitcodeError::InvalidRecord);
Devang Patelaf206b82009-09-18 19:26:43 +00002299 Instruction *Inst = InstructionList[Record[0]];
2300 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00002301 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00002302 DenseMap<unsigned, unsigned>::iterator I =
2303 MDKindMap.find(Kind);
2304 if (I == MDKindMap.end())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002305 return Error(BitcodeError::InvalidID);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002306 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman43aa8f02010-07-20 21:42:28 +00002307 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00002308 if (I->second == LLVMContext::MD_tbaa)
2309 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00002310 }
2311 break;
2312 }
2313 }
2314 }
Devang Patelaf206b82009-09-18 19:26:43 +00002315}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002316
Chris Lattner85b7b402007-05-01 05:52:21 +00002317/// ParseFunctionBody - Lazily parse the specified function body block.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002318std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002319 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002320 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002321
Nick Lewyckya72e1af2010-02-25 08:30:17 +00002322 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00002323 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00002324 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002325
Chris Lattner85b7b402007-05-01 05:52:21 +00002326 // Add all the function arguments to the value table.
2327 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2328 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002329
Chris Lattner83930552007-05-01 07:01:57 +00002330 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00002331 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00002332 unsigned CurBBNo = 0;
2333
Chris Lattner07d09ed2010-04-03 02:17:50 +00002334 DebugLoc LastLoc;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002335
Chris Lattner85b7b402007-05-01 05:52:21 +00002336 // Read all the records.
2337 SmallVector<uint64_t, 64> Record;
2338 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002339 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002340
Chris Lattner27d38752013-01-20 02:13:19 +00002341 switch (Entry.Kind) {
2342 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002343 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002344 case BitstreamEntry::EndBlock:
2345 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00002346
Chris Lattner27d38752013-01-20 02:13:19 +00002347 case BitstreamEntry::SubBlock:
2348 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00002349 default: // Skip unknown content.
2350 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002351 return Error(BitcodeError::InvalidRecord);
Chris Lattner85b7b402007-05-01 05:52:21 +00002352 break;
2353 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002354 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002355 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00002356 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00002357 break;
2358 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002359 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002360 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00002361 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002362 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002363 if (std::error_code EC = ParseMetadataAttachment())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002364 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002365 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002366 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002367 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002368 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002369 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002370 case bitc::USELIST_BLOCK_ID:
2371 if (std::error_code EC = ParseUseLists())
2372 return EC;
2373 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002374 }
2375 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002376
Chris Lattner27d38752013-01-20 02:13:19 +00002377 case BitstreamEntry::Record:
2378 // The interesting case.
2379 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002380 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002381
Chris Lattner85b7b402007-05-01 05:52:21 +00002382 // Read a record.
2383 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002384 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002385 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002386 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00002387 default: // Default behavior: reject
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002388 return Error(BitcodeError::InvalidValue);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002389 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00002390 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002391 return Error(BitcodeError::InvalidRecord);
Chris Lattner85b7b402007-05-01 05:52:21 +00002392 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00002393 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002394
2395 // See if anything took the address of blocks in this function.
2396 auto BBFRI = BasicBlockFwdRefs.find(F);
2397 if (BBFRI == BasicBlockFwdRefs.end()) {
2398 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2399 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2400 } else {
2401 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002402 // Check for invalid basic block references.
2403 if (BBRefs.size() > FunctionBBs.size())
2404 return Error(BitcodeError::InvalidID);
2405 assert(!BBRefs.empty() && "Unexpected empty array");
2406 assert(!BBRefs.front() && "Invalid reference to entry block");
2407 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2408 ++I)
2409 if (I < RE && BBRefs[I]) {
2410 BBRefs[I]->insertInto(F);
2411 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002412 } else {
2413 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2414 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002415
2416 // Erase from the table.
2417 BasicBlockFwdRefs.erase(BBFRI);
2418 }
2419
Chris Lattner83930552007-05-01 07:01:57 +00002420 CurBB = FunctionBBs[0];
2421 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002422 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002423
Chris Lattner07d09ed2010-04-03 02:17:50 +00002424 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2425 // This record indicates that the last instruction is at the same
2426 // location as the previous instruction with a location.
Craig Topper2617dcc2014-04-15 06:32:26 +00002427 I = nullptr;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002428
Chris Lattner07d09ed2010-04-03 02:17:50 +00002429 // Get the last instruction emitted.
2430 if (CurBB && !CurBB->empty())
2431 I = &CurBB->back();
2432 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2433 !FunctionBBs[CurBBNo-1]->empty())
2434 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002435
Craig Topper2617dcc2014-04-15 06:32:26 +00002436 if (!I)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002437 return Error(BitcodeError::InvalidRecord);
Chris Lattner07d09ed2010-04-03 02:17:50 +00002438 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002439 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002440 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002441
Chris Lattnerc44070802011-06-17 18:17:37 +00002442 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Craig Topper2617dcc2014-04-15 06:32:26 +00002443 I = nullptr; // Get the last instruction emitted.
Chris Lattner07d09ed2010-04-03 02:17:50 +00002444 if (CurBB && !CurBB->empty())
2445 I = &CurBB->back();
2446 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2447 !FunctionBBs[CurBBNo-1]->empty())
2448 I = &FunctionBBs[CurBBNo-1]->back();
Craig Topper2617dcc2014-04-15 06:32:26 +00002449 if (!I || Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002450 return Error(BitcodeError::InvalidRecord);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002451
Chris Lattner07d09ed2010-04-03 02:17:50 +00002452 unsigned Line = Record[0], Col = Record[1];
2453 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002454
Craig Topper2617dcc2014-04-15 06:32:26 +00002455 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002456 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2457 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2458 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2459 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002460 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002461 continue;
2462 }
2463
Chris Lattnere9759c22007-05-06 00:21:25 +00002464 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2465 unsigned OpNum = 0;
2466 Value *LHS, *RHS;
2467 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002468 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00002469 OpNum+1 > Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002470 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002471
Dan Gohman0ebd6962009-07-20 21:19:07 +00002472 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00002473 if (Opc == -1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002474 return Error(BitcodeError::InvalidRecord);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002475 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00002476 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00002477 if (OpNum < Record.size()) {
2478 if (Opc == Instruction::Add ||
2479 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002480 Opc == Instruction::Mul ||
2481 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00002482 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00002483 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00002484 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00002485 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00002486 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002487 Opc == Instruction::UDiv ||
2488 Opc == Instruction::LShr ||
2489 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002490 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002491 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002492 } else if (isa<FPMathOperator>(I)) {
2493 FastMathFlags FMF;
Michael Ilseman65f14352012-12-09 21:12:04 +00002494 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2495 FMF.setUnsafeAlgebra();
2496 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2497 FMF.setNoNaNs();
2498 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2499 FMF.setNoInfs();
2500 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2501 FMF.setNoSignedZeros();
2502 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2503 FMF.setAllowReciprocal();
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002504 if (FMF.any())
2505 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00002506 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002507
Dan Gohman1b849082009-09-07 23:54:19 +00002508 }
Chris Lattner85b7b402007-05-01 05:52:21 +00002509 break;
2510 }
Chris Lattnere9759c22007-05-06 00:21:25 +00002511 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2512 unsigned OpNum = 0;
2513 Value *Op;
2514 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2515 OpNum+2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002516 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002517
Chris Lattner229907c2011-07-18 04:54:35 +00002518 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnere9759c22007-05-06 00:21:25 +00002519 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002520 if (Opc == -1 || !ResTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002521 return Error(BitcodeError::InvalidRecord);
Craig Topper2617dcc2014-04-15 06:32:26 +00002522 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002523 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2524 if (Temp) {
2525 InstructionList.push_back(Temp);
2526 CurBB->getInstList().push_back(Temp);
2527 }
2528 } else {
2529 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2530 }
Devang Patelaf206b82009-09-18 19:26:43 +00002531 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00002532 break;
2533 }
Dan Gohman1639c392009-07-27 21:53:46 +00002534 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattnere14cb882007-05-04 19:11:41 +00002535 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002536 unsigned OpNum = 0;
2537 Value *BasePtr;
2538 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002539 return Error(BitcodeError::InvalidRecord);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002540
Chris Lattner5285b5e2007-05-02 05:46:45 +00002541 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002542 while (OpNum != Record.size()) {
2543 Value *Op;
2544 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002545 return Error(BitcodeError::InvalidRecord);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002546 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002547 }
2548
Jay Foadd1b78492011-07-25 09:48:08 +00002549 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002550 InstructionList.push_back(I);
Dan Gohman1639c392009-07-27 21:53:46 +00002551 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohman1b849082009-09-07 23:54:19 +00002552 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002553 break;
2554 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002555
Dan Gohman1ecaf452008-05-31 00:58:22 +00002556 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2557 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00002558 unsigned OpNum = 0;
2559 Value *Agg;
2560 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002561 return Error(BitcodeError::InvalidRecord);
Dan Gohman30499842008-05-23 01:55:30 +00002562
Dan Gohman1ecaf452008-05-31 00:58:22 +00002563 SmallVector<unsigned, 4> EXTRACTVALIdx;
2564 for (unsigned RecSize = Record.size();
2565 OpNum != RecSize; ++OpNum) {
2566 uint64_t Index = Record[OpNum];
2567 if ((unsigned)Index != Index)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002568 return Error(BitcodeError::InvalidValue);
Dan Gohman1ecaf452008-05-31 00:58:22 +00002569 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohman30499842008-05-23 01:55:30 +00002570 }
2571
Jay Foad57aa6362011-07-13 10:26:04 +00002572 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002573 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00002574 break;
2575 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002576
Dan Gohman1ecaf452008-05-31 00:58:22 +00002577 case bitc::FUNC_CODE_INST_INSERTVAL: {
2578 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00002579 unsigned OpNum = 0;
2580 Value *Agg;
2581 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002582 return Error(BitcodeError::InvalidRecord);
Dan Gohman30499842008-05-23 01:55:30 +00002583 Value *Val;
2584 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002585 return Error(BitcodeError::InvalidRecord);
Dan Gohman30499842008-05-23 01:55:30 +00002586
Dan Gohman1ecaf452008-05-31 00:58:22 +00002587 SmallVector<unsigned, 4> INSERTVALIdx;
2588 for (unsigned RecSize = Record.size();
2589 OpNum != RecSize; ++OpNum) {
2590 uint64_t Index = Record[OpNum];
2591 if ((unsigned)Index != Index)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002592 return Error(BitcodeError::InvalidValue);
Dan Gohman1ecaf452008-05-31 00:58:22 +00002593 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohman30499842008-05-23 01:55:30 +00002594 }
2595
Jay Foad57aa6362011-07-13 10:26:04 +00002596 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002597 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00002598 break;
2599 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002600
Chris Lattnere9759c22007-05-06 00:21:25 +00002601 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00002602 // obsolete form of select
2603 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00002604 unsigned OpNum = 0;
2605 Value *TrueVal, *FalseVal, *Cond;
2606 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002607 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2608 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002609 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002610
Dan Gohmanc5d28922008-09-16 01:01:33 +00002611 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00002612 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00002613 break;
2614 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002615
Dan Gohmanc5d28922008-09-16 01:01:33 +00002616 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2617 // new form of select
2618 // handles select i1 or select [N x i1]
2619 unsigned OpNum = 0;
2620 Value *TrueVal, *FalseVal, *Cond;
2621 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002622 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00002623 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002624 return Error(BitcodeError::InvalidRecord);
Dan Gohmanc579d972008-09-09 01:02:47 +00002625
2626 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00002627 if (VectorType* vector_type =
2628 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00002629 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002630 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002631 return Error(BitcodeError::InvalidTypeForValue);
Dan Gohmanc579d972008-09-09 01:02:47 +00002632 } else {
2633 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002635 return Error(BitcodeError::InvalidTypeForValue);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636 }
2637
Gabor Greife9ecc682008-04-06 20:25:17 +00002638 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00002639 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002640 break;
2641 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002642
Chris Lattner1fc27f02007-05-02 05:16:49 +00002643 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00002644 unsigned OpNum = 0;
2645 Value *Vec, *Idx;
2646 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002647 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002648 return Error(BitcodeError::InvalidRecord);
Eric Christopherc9742252009-07-25 02:28:41 +00002649 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00002650 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002651 break;
2652 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002653
Chris Lattner1fc27f02007-05-02 05:16:49 +00002654 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00002655 unsigned OpNum = 0;
2656 Value *Vec, *Elt, *Idx;
2657 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002658 popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00002659 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002660 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002661 return Error(BitcodeError::InvalidRecord);
Gabor Greife9ecc682008-04-06 20:25:17 +00002662 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00002663 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002664 break;
2665 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666
Chris Lattnere9759c22007-05-06 00:21:25 +00002667 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2668 unsigned OpNum = 0;
2669 Value *Vec1, *Vec2, *Mask;
2670 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002671 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002672 return Error(BitcodeError::InvalidRecord);
Chris Lattnere9759c22007-05-06 00:21:25 +00002673
Mon P Wang25f01062008-11-10 04:46:22 +00002674 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002675 return Error(BitcodeError::InvalidRecord);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002676 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00002677 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002678 break;
2679 }
Mon P Wang25f01062008-11-10 04:46:22 +00002680
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002681 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2682 // Old form of ICmp/FCmp returning bool
2683 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2684 // both legal on vectors but had different behaviour.
2685 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2686 // FCmp/ICmp returning bool or vector of bool
2687
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002688 unsigned OpNum = 0;
2689 Value *LHS, *RHS;
2690 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002691 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002692 OpNum+1 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002693 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002694
Duncan Sands9dff9be2010-02-15 16:12:20 +00002695 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohmanad1f0a12009-08-25 23:17:54 +00002696 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002697 else
Dan Gohmanad1f0a12009-08-25 23:17:54 +00002698 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00002699 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00002700 break;
2701 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002702
Chris Lattnere53603e2007-05-02 04:27:25 +00002703 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00002704 {
2705 unsigned Size = Record.size();
2706 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002707 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00002709 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002710 }
Devang Patelbbfd8742008-02-26 01:29:32 +00002711
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002712 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00002713 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00002714 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002715 return Error(BitcodeError::InvalidRecord);
Chris Lattnerf1c87102011-06-17 18:09:11 +00002716 if (OpNum != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002717 return Error(BitcodeError::InvalidRecord);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002718
Chris Lattnerf1c87102011-06-17 18:09:11 +00002719 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002720 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002721 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00002722 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00002723 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00002724 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002725 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002726 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002727 if (!TrueDest)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002728 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002729
Devang Patelaf206b82009-09-18 19:26:43 +00002730 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00002731 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002732 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00002733 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00002734 else {
2735 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002736 Value *Cond = getValue(Record, 2, NextValueNo,
2737 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00002738 if (!FalseDest || !Cond)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002739 return Error(BitcodeError::InvalidRecord);
Gabor Greife9ecc682008-04-06 20:25:17 +00002740 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002742 }
2743 break;
2744 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00002745 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002746 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002747 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00002748 // "New" SwitchInst format with case ranges. The changes to write this
2749 // format were reverted but we still recognize bitcode that uses it.
2750 // Hopefully someday we will have support for case ranges and can use
2751 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002752
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002753 Type *OpTy = getTypeByID(Record[1]);
2754 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2755
Jan Wen Voungafaced02012-10-11 20:20:40 +00002756 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002757 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002758 if (!OpTy || !Cond || !Default)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002759 return Error(BitcodeError::InvalidRecord);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002760
2761 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002762
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002763 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2764 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002765
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002766 unsigned CurIdx = 5;
2767 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00002768 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002769 unsigned NumItems = Record[CurIdx++];
2770 for (unsigned ci = 0; ci != NumItems; ++ci) {
2771 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002772
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002773 APInt Low;
2774 unsigned ActiveWords = 1;
2775 if (ValueBitWidth > 64)
2776 ActiveWords = Record[CurIdx++];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002777 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2778 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002779 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00002780
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002781 if (!isSingleNumber) {
2782 ActiveWords = 1;
2783 if (ValueBitWidth > 64)
2784 ActiveWords = Record[CurIdx++];
2785 APInt High =
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002786 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2787 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002788 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00002789
2790 // FIXME: It is not clear whether values in the range should be
2791 // compared as signed or unsigned values. The partially
2792 // implemented changes that used this format in the past used
2793 // unsigned comparisons.
2794 for ( ; Low.ule(High); ++Low)
2795 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002796 } else
Bob Wilsone4077362013-09-09 19:14:35 +00002797 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002798 }
2799 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00002800 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2801 cve = CaseVals.end(); cvi != cve; ++cvi)
2802 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002803 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002804 I = SI;
2805 break;
2806 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002807
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002808 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002809
Chris Lattner5285b5e2007-05-02 05:46:45 +00002810 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002811 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002812 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002813 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002814 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002815 if (!OpTy || !Cond || !Default)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002816 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002817 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00002818 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00002819 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002820 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002821 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00002822 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2823 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002824 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00002825 delete SI;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002826 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002827 }
2828 SI->addCase(CaseVal, DestBB);
2829 }
2830 I = SI;
2831 break;
2832 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002833 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00002834 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002835 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002836 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002837 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002838 if (!OpTy || !Address)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002839 return Error(BitcodeError::InvalidRecord);
Chris Lattner3ed871f2009-10-27 19:13:16 +00002840 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002841 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00002842 InstructionList.push_back(IBI);
2843 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2844 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2845 IBI->addDestination(DestBB);
2846 } else {
2847 delete IBI;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002848 return Error(BitcodeError::InvalidRecord);
Chris Lattner3ed871f2009-10-27 19:13:16 +00002849 }
2850 }
2851 I = IBI;
2852 break;
2853 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002854
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002855 case bitc::FUNC_CODE_INST_INVOKE: {
2856 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002857 if (Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002858 return Error(BitcodeError::InvalidRecord);
Bill Wendlinge94d8432012-12-07 23:16:57 +00002859 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002860 unsigned CCInfo = Record[1];
2861 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2862 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002863
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002864 unsigned OpNum = 4;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002865 Value *Callee;
2866 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002867 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002868
Chris Lattner229907c2011-07-18 04:54:35 +00002869 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00002870 FunctionType *FTy = !CalleeTy ? nullptr :
Chris Lattner5285b5e2007-05-02 05:46:45 +00002871 dyn_cast<FunctionType>(CalleeTy->getElementType());
2872
2873 // Check that the right number of fixed parameters are here.
Craig Topper2617dcc2014-04-15 06:32:26 +00002874 if (!FTy || !NormalBB || !UnwindBB ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002875 Record.size() < OpNum+FTy->getNumParams())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002876 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002877
Chris Lattner5285b5e2007-05-02 05:46:45 +00002878 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002879 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002880 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2881 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00002882 if (!Ops.back())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002883 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002884 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002885
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002886 if (!FTy->isVarArg()) {
2887 if (Record.size() != OpNum)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002888 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002889 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002890 // Read type/value pairs for varargs params.
2891 while (OpNum != Record.size()) {
2892 Value *Op;
2893 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002894 return Error(BitcodeError::InvalidRecord);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002895 Ops.push_back(Op);
2896 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00002897 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002898
Jay Foad5bd375a2011-07-15 08:37:34 +00002899 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00002900 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00002901 cast<InvokeInst>(I)->setCallingConv(
2902 static_cast<CallingConv::ID>(CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00002903 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002904 break;
2905 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002906 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2907 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00002908 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00002909 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002910 return Error(BitcodeError::InvalidRecord);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002911 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00002912 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002913 break;
2914 }
Chris Lattnere53603e2007-05-02 04:27:25 +00002915 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00002916 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00002917 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00002918 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00002919 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00002920 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002921 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002922 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002923 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002924 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002925
Jay Foad52131342011-03-30 11:28:46 +00002926 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00002927 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002928
Chris Lattnere14cb882007-05-04 19:11:41 +00002929 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002930 Value *V;
2931 // With the new function encoding, it is possible that operands have
2932 // negative IDs (for forward references). Use a signed VBR
2933 // representation to keep the encoding small.
2934 if (UseRelativeIDs)
2935 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2936 else
2937 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00002938 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002939 if (!V || !BB)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002940 return Error(BitcodeError::InvalidRecord);
Chris Lattnerc332bba2007-05-03 18:58:09 +00002941 PN->addIncoming(V, BB);
2942 }
2943 I = PN;
2944 break;
2945 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002946
Bill Wendlingfae14752011-08-12 20:24:12 +00002947 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2948 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2949 unsigned Idx = 0;
2950 if (Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002951 return Error(BitcodeError::InvalidRecord);
Bill Wendlingfae14752011-08-12 20:24:12 +00002952 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002953 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002954 return Error(BitcodeError::InvalidRecord);
Craig Topper2617dcc2014-04-15 06:32:26 +00002955 Value *PersFn = nullptr;
Bill Wendlingfae14752011-08-12 20:24:12 +00002956 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002957 return Error(BitcodeError::InvalidRecord);
Bill Wendlingfae14752011-08-12 20:24:12 +00002958
2959 bool IsCleanup = !!Record[Idx++];
2960 unsigned NumClauses = Record[Idx++];
2961 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2962 LP->setCleanup(IsCleanup);
2963 for (unsigned J = 0; J != NumClauses; ++J) {
2964 LandingPadInst::ClauseType CT =
2965 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2966 Value *Val;
2967
2968 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2969 delete LP;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002970 return Error(BitcodeError::InvalidRecord);
Bill Wendlingfae14752011-08-12 20:24:12 +00002971 }
2972
2973 assert((CT != LandingPadInst::Catch ||
2974 !isa<ArrayType>(Val->getType())) &&
2975 "Catch clause has a invalid type!");
2976 assert((CT != LandingPadInst::Filter ||
2977 isa<ArrayType>(Val->getType())) &&
2978 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002979 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00002980 }
2981
2982 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00002983 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00002984 break;
2985 }
2986
Chris Lattnerf1c87102011-06-17 18:09:11 +00002987 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2988 if (Record.size() != 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002989 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002990 PointerType *Ty =
Chris Lattnerc332bba2007-05-03 18:58:09 +00002991 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattner229907c2011-07-18 04:54:35 +00002992 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerf1c87102011-06-17 18:09:11 +00002993 Value *Size = getFnValueByID(Record[2], OpTy);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002994 unsigned AlignRecord = Record[3];
2995 bool InAlloca = AlignRecord & (1 << 5);
2996 unsigned Align = AlignRecord & ((1 << 5) - 1);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002997 if (!Ty || !Size)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002998 return Error(BitcodeError::InvalidRecord);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002999 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3000 AI->setUsedWithInAlloca(InAlloca);
3001 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00003002 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00003003 break;
3004 }
Chris Lattner9f600c52007-05-03 22:04:19 +00003005 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003006 unsigned OpNum = 0;
3007 Value *Op;
3008 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3009 OpNum+2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003010 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003011
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003012 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patelaf206b82009-09-18 19:26:43 +00003013 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00003014 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00003015 }
Eli Friedman59b66882011-08-09 23:02:53 +00003016 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3017 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3018 unsigned OpNum = 0;
3019 Value *Op;
3020 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3021 OpNum+4 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003022 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003023
3024 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3025 if (Ordering == NotAtomic || Ordering == Release ||
3026 Ordering == AcquireRelease)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003027 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003028 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003029 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003030 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3031
3032 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3033 Ordering, SynchScope);
3034 InstructionList.push_back(I);
3035 break;
3036 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003037 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003038 unsigned OpNum = 0;
3039 Value *Val, *Ptr;
3040 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003041 popValue(Record, OpNum, NextValueNo,
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003042 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3043 OpNum+2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003044 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003045
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003046 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patelaf206b82009-09-18 19:26:43 +00003047 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003048 break;
3049 }
Eli Friedman59b66882011-08-09 23:02:53 +00003050 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3051 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3052 unsigned OpNum = 0;
3053 Value *Val, *Ptr;
3054 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003055 popValue(Record, OpNum, NextValueNo,
Eli Friedman59b66882011-08-09 23:02:53 +00003056 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3057 OpNum+4 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003058 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003059
3060 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00003061 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00003062 Ordering == AcquireRelease)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003063 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003064 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3065 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003066 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003067
3068 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3069 Ordering, SynchScope);
3070 InstructionList.push_back(I);
3071 break;
3072 }
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003073 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00003074 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00003075 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003076 unsigned OpNum = 0;
3077 Value *Ptr, *Cmp, *New;
3078 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003079 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003080 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003081 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003082 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
Tim Northover420a2162014-06-13 14:24:07 +00003083 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003084 return Error(BitcodeError::InvalidRecord);
Tim Northovere94a5182014-03-11 10:48:52 +00003085 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3086 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003087 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003088 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
Tim Northovere94a5182014-03-11 10:48:52 +00003089
3090 AtomicOrdering FailureOrdering;
3091 if (Record.size() < 7)
3092 FailureOrdering =
3093 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3094 else
3095 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3096
3097 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3098 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003099 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00003100
3101 if (Record.size() < 8) {
3102 // Before weak cmpxchgs existed, the instruction simply returned the
3103 // value loaded from memory, so bitcode files from that era will be
3104 // expecting the first component of a modern cmpxchg.
3105 CurBB->getInstList().push_back(I);
3106 I = ExtractValueInst::Create(I, 0);
3107 } else {
3108 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3109 }
3110
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003111 InstructionList.push_back(I);
3112 break;
3113 }
3114 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3115 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3116 unsigned OpNum = 0;
3117 Value *Ptr, *Val;
3118 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003119 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003120 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3121 OpNum+4 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003122 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003123 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3124 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3125 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003126 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003127 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman59b66882011-08-09 23:02:53 +00003128 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003129 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003130 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3131 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3132 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3133 InstructionList.push_back(I);
3134 break;
3135 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00003136 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3137 if (2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003138 return Error(BitcodeError::InvalidRecord);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003139 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3140 if (Ordering == NotAtomic || Ordering == Unordered ||
3141 Ordering == Monotonic)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003142 return Error(BitcodeError::InvalidRecord);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003143 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3144 I = new FenceInst(Context, Ordering, SynchScope);
3145 InstructionList.push_back(I);
3146 break;
3147 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003148 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003149 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3150 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003151 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003152
Bill Wendlinge94d8432012-12-07 23:16:57 +00003153 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003154 unsigned CCInfo = Record[1];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003155
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003156 unsigned OpNum = 2;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003157 Value *Callee;
3158 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003159 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003160
Chris Lattner229907c2011-07-18 04:54:35 +00003161 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00003162 FunctionType *FTy = nullptr;
Chris Lattner9f600c52007-05-03 22:04:19 +00003163 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003164 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003165 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003166
Chris Lattner9f600c52007-05-03 22:04:19 +00003167 SmallVector<Value*, 16> Args;
3168 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003169 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003170 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00003171 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00003172 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00003173 Args.push_back(getValue(Record, OpNum, NextValueNo,
3174 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003175 if (!Args.back())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003176 return Error(BitcodeError::InvalidRecord);
Chris Lattner9f600c52007-05-03 22:04:19 +00003177 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003178
Chris Lattner9f600c52007-05-03 22:04:19 +00003179 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00003180 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003181 if (OpNum != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003182 return Error(BitcodeError::InvalidRecord);
Chris Lattner9f600c52007-05-03 22:04:19 +00003183 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003184 while (OpNum != Record.size()) {
3185 Value *Op;
3186 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003187 return Error(BitcodeError::InvalidRecord);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003188 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00003189 }
3190 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003191
Jay Foad5bd375a2011-07-15 08:37:34 +00003192 I = CallInst::Create(Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00003193 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003194 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00003195 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3196 CallInst::TailCallKind TCK = CallInst::TCK_None;
3197 if (CCInfo & 1)
3198 TCK = CallInst::TCK_Tail;
3199 if (CCInfo & (1 << 14))
3200 TCK = CallInst::TCK_MustTail;
3201 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00003202 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00003203 break;
3204 }
3205 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3206 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003207 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00003208 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003209 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003210 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00003211 if (!OpTy || !Op || !ResTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003212 return Error(BitcodeError::InvalidRecord);
Chris Lattner9f600c52007-05-03 22:04:19 +00003213 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00003214 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00003215 break;
3216 }
Chris Lattner83930552007-05-01 07:01:57 +00003217 }
3218
3219 // Add instruction to end of current BB. If there is no current BB, reject
3220 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00003221 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00003222 delete I;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003223 return Error(BitcodeError::InvalidInstructionWithNoBB);
Chris Lattner83930552007-05-01 07:01:57 +00003224 }
3225 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003226
Chris Lattner83930552007-05-01 07:01:57 +00003227 // If this was a terminator instruction, move to the next block.
3228 if (isa<TerminatorInst>(I)) {
3229 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00003230 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00003231 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003232
Chris Lattner83930552007-05-01 07:01:57 +00003233 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003234 if (I && !I->getType()->isVoidTy())
Chris Lattner83930552007-05-01 07:01:57 +00003235 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00003236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003237
Chris Lattner27d38752013-01-20 02:13:19 +00003238OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00003239
Chris Lattner83930552007-05-01 07:01:57 +00003240 // Check the function list for unresolved values.
3241 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003242 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00003243 // We found at least one unresolved value. Nuke them all to avoid leaks.
3244 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00003245 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003246 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00003247 delete A;
3248 }
3249 }
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003250 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
Chris Lattner83930552007-05-01 07:01:57 +00003251 }
Chris Lattner83930552007-05-01 07:01:57 +00003252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003253
Dan Gohman9b9ff462010-08-25 20:23:38 +00003254 // FIXME: Check for unresolved forward-declared metadata references
3255 // and clean up leaks.
3256
Chris Lattner85b7b402007-05-01 05:52:21 +00003257 // Trim the value list down to the size it was before we parsed this function.
3258 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00003259 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00003260 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003261 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003262}
3263
Rafael Espindola7d712032013-11-05 17:16:08 +00003264/// Find the function body in the bitcode stream
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003265std::error_code BitcodeReader::FindFunctionInStream(
3266 Function *F,
3267 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003268 while (DeferredFunctionInfoIterator->second == 0) {
3269 if (Stream.AtEndOfStream())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003270 return Error(BitcodeError::CouldNotFindFunctionInStream);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003271 // ParseModule will parse the next body in the stream and set its
3272 // position in the DeferredFunctionInfo map.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003273 if (std::error_code EC = ParseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00003274 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003275 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003276 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003277}
3278
Chris Lattner9eeada92007-05-18 04:02:46 +00003279//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003280// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00003281//===----------------------------------------------------------------------===//
3282
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00003283void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00003284
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003285std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003286 Function *F = dyn_cast<Function>(GV);
3287 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003288 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003289 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003290
3291 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00003292 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003293 // If its position is recorded as 0, its body is somewhere in the stream
3294 // but we haven't seen it yet.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003295 if (DFII->second == 0 && LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003296 if (std::error_code EC = FindFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003297 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003298
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003299 // Move the bit stream to the saved position of the deferred function body.
3300 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003301
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003302 if (std::error_code EC = ParseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003303 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003304 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00003305
3306 // Upgrade any old intrinsic calls in the function.
3307 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3308 E = UpgradedIntrinsics.end(); I != E; ++I) {
3309 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003310 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3311 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003312 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3313 UpgradeIntrinsicCall(CI, I->second);
3314 }
3315 }
3316 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003317
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003318 // Bring in any functions that this function forward-referenced via
3319 // blockaddresses.
3320 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00003321}
3322
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003323bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3324 const Function *F = dyn_cast<Function>(GV);
3325 if (!F || F->isDeclaration())
3326 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003327
3328 // Dematerializing F would leave dangling references that wouldn't be
3329 // reconnected on re-materialization.
3330 if (BlockAddressesTaken.count(F))
3331 return false;
3332
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003333 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3334}
3335
3336void BitcodeReader::Dematerialize(GlobalValue *GV) {
3337 Function *F = dyn_cast<Function>(GV);
3338 // If this function isn't dematerializable, this is a noop.
3339 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00003340 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003341
Chris Lattner9eeada92007-05-18 04:02:46 +00003342 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003343
Chris Lattner9eeada92007-05-18 04:02:46 +00003344 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00003345 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003346 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00003347}
3348
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003349std::error_code BitcodeReader::MaterializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003350 assert(M == TheModule &&
3351 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003352
3353 // Promise to materialize all forward references.
3354 WillMaterializeAllForwardRefs = true;
3355
Chris Lattner06310bf2009-06-16 05:15:21 +00003356 // Iterate over the module, deserializing any functions that are still on
3357 // disk.
3358 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003359 F != E; ++F) {
3360 if (F->isMaterializable()) {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003361 if (std::error_code EC = Materialize(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003362 return EC;
3363 }
3364 }
Derek Schuff92ef9752012-02-29 00:07:09 +00003365 // At this point, if there are any function bodies, the current bit is
3366 // pointing to the END_BLOCK record after them. Now make sure the rest
3367 // of the bits in the module have been read.
3368 if (NextUnreadBit)
3369 ParseModule(true);
3370
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003371 // Check that all block address forward references got resolved (as we
3372 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003373 if (!BasicBlockFwdRefs.empty())
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003374 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3375
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003376 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3377 // delete the old functions to clean up. We can't do this unless the entire
3378 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00003379 // with calls to the old function.
3380 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3381 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3382 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003383 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3384 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003385 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3386 UpgradeIntrinsicCall(CI, I->second);
3387 }
Chris Lattner647cffb2009-04-01 01:43:03 +00003388 if (!I->first->use_empty())
3389 I->first->replaceAllUsesWith(I->second);
Chandler Carruth7132e002007-08-04 01:51:18 +00003390 I->first->eraseFromParent();
3391 }
3392 }
3393 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patel80ae3492009-08-28 23:24:31 +00003394
Manman Ren209b17c2013-09-28 00:22:27 +00003395 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3396 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3397
Manman Ren8b4306c2013-12-02 21:29:56 +00003398 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003399 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00003400}
3401
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003402std::error_code BitcodeReader::InitStream() {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003403 if (LazyStreamer)
3404 return InitLazyStream();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003405 return InitStreamFromBuffer();
3406}
3407
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003408std::error_code BitcodeReader::InitStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00003409 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003410 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3411
Rafael Espindola27435252014-07-29 21:01:24 +00003412 if (Buffer->getBufferSize() & 3)
3413 return Error(BitcodeError::InvalidBitcodeSignature);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003414
3415 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3416 // The magic number is 0x0B17C0DE stored in little endian.
3417 if (isBitcodeWrapper(BufPtr, BufEnd))
3418 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003419 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003420
3421 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3422 Stream.init(*StreamFile);
3423
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003424 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003425}
3426
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003427std::error_code BitcodeReader::InitLazyStream() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003428 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3429 // see it.
3430 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3431 StreamFile.reset(new BitstreamReader(Bytes));
3432 Stream.init(*StreamFile);
3433
3434 unsigned char buf[16];
Benjamin Kramer534d3a42013-05-24 10:54:58 +00003435 if (Bytes->readBytes(0, 16, buf) == -1)
Rafael Espindola27435252014-07-29 21:01:24 +00003436 return Error(BitcodeError::InvalidBitcodeSignature);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003437
3438 if (!isBitcode(buf, buf + 16))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003439 return Error(BitcodeError::InvalidBitcodeSignature);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003440
3441 if (isBitcodeWrapper(buf, buf + 4)) {
3442 const unsigned char *bitcodeStart = buf;
3443 const unsigned char *bitcodeEnd = buf + 16;
3444 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3445 Bytes->dropLeadingBytes(bitcodeStart - buf);
3446 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3447 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003448 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00003449}
3450
3451namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00003452class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00003453 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003454 return "llvm.bitcode";
3455 }
Craig Topper73156022014-03-02 09:09:27 +00003456 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003457 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003458 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003459 case BitcodeError::ConflictingMETADATA_KINDRecords:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003460 return "Conflicting METADATA_KIND records";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003461 case BitcodeError::CouldNotFindFunctionInStream:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003462 return "Could not find function in stream";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003463 case BitcodeError::ExpectedConstant:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003464 return "Expected a constant";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003465 case BitcodeError::InsufficientFunctionProtos:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003466 return "Insufficient function protos";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003467 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003468 return "Invalid bitcode signature";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003469 case BitcodeError::InvalidBitcodeWrapperHeader:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003470 return "Invalid bitcode wrapper header";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003471 case BitcodeError::InvalidConstantReference:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003472 return "Invalid ronstant reference";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003473 case BitcodeError::InvalidID:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003474 return "Invalid ID";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003475 case BitcodeError::InvalidInstructionWithNoBB:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003476 return "Invalid instruction with no BB";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003477 case BitcodeError::InvalidRecord:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003478 return "Invalid record";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003479 case BitcodeError::InvalidTypeForValue:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003480 return "Invalid type for value";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003481 case BitcodeError::InvalidTYPETable:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003482 return "Invalid TYPE table";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003483 case BitcodeError::InvalidType:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003484 return "Invalid type";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003485 case BitcodeError::MalformedBlock:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003486 return "Malformed block";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003487 case BitcodeError::MalformedGlobalInitializerSet:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003488 return "Malformed global initializer set";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003489 case BitcodeError::InvalidMultipleBlocks:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003490 return "Invalid multiple blocks";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003491 case BitcodeError::NeverResolvedValueFoundInFunction:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003492 return "Never resolved value found in function";
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003493 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3494 return "Never resolved function from blockaddress";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003495 case BitcodeError::InvalidValue:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003496 return "Invalid value";
3497 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00003498 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00003499 }
3500};
3501}
3502
Chris Bieneman770163e2014-09-19 20:29:02 +00003503static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3504
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003505const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00003506 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003507}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003508
Chris Lattner6694f602007-04-29 07:54:31 +00003509//===----------------------------------------------------------------------===//
3510// External interface
3511//===----------------------------------------------------------------------===//
3512
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003513/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00003514///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003515/// This isn't always used in a lazy context. In particular, it's also used by
3516/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3517/// in forward-referenced functions from block address references.
3518///
3519/// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3520/// materialize everything -- in particular, if this isn't truly lazy.
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003521static ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00003522getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003523 LLVMContext &Context, bool WillMaterializeAll) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003524 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003525 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003526 M->setMaterializer(R);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003527
3528 auto cleanupOnError = [&](std::error_code EC) {
Rafael Espindola8fb31112014-06-18 20:07:35 +00003529 R->releaseBuffer(); // Never take ownership on error.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003530 delete M; // Also deletes R.
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00003531 return EC;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003532 };
Rafael Espindolab7993462012-01-02 07:49:53 +00003533
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003534 if (std::error_code EC = R->ParseBitcodeInto(M))
3535 return cleanupOnError(EC);
3536
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003537 if (!WillMaterializeAll)
3538 // Resolve forward references from blockaddresses.
3539 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3540 return cleanupOnError(EC);
Rafael Espindolab7993462012-01-02 07:49:53 +00003541
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003542 Buffer.release(); // The BitcodeReader owns it now.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003543 return M;
Chris Lattner6694f602007-04-29 07:54:31 +00003544}
3545
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003546ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00003547llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003548 LLVMContext &Context) {
Rafael Espindola68812152014-09-03 17:31:46 +00003549 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003550}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003551
3552Module *llvm::getStreamedBitcodeModule(const std::string &name,
3553 DataStreamer *streamer,
3554 LLVMContext &Context,
3555 std::string *ErrMsg) {
3556 Module *M = new Module(name, Context);
3557 BitcodeReader *R = new BitcodeReader(streamer, Context);
3558 M->setMaterializer(R);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003559 if (std::error_code EC = R->ParseBitcodeInto(M)) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003560 if (ErrMsg)
Rafael Espindola48da4f42013-11-04 16:16:24 +00003561 *ErrMsg = EC.message();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003562 delete M; // Also deletes R.
Craig Topper2617dcc2014-04-15 06:32:26 +00003563 return nullptr;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003564 }
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003565 return M;
3566}
3567
Rafael Espindolad96d5532014-08-26 21:49:01 +00003568ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
Rafael Espindola8f31e212014-01-15 01:08:23 +00003569 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00003570 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola68812152014-09-03 17:31:46 +00003571 ErrorOr<Module *> ModuleOrErr =
3572 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Rafael Espindola8f31e212014-01-15 01:08:23 +00003573 if (!ModuleOrErr)
3574 return ModuleOrErr;
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00003575 Module *M = ModuleOrErr.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003576 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolad96d5532014-08-26 21:49:01 +00003577 if (std::error_code EC = M->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003578 delete M;
Rafael Espindola8f31e212014-01-15 01:08:23 +00003579 return EC;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003580 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003581
Chad Rosierca2567b2011-12-07 21:44:12 +00003582 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3583 // written. We must defer until the Module has been fully materialized.
3584
Chris Lattner6694f602007-04-29 07:54:31 +00003585 return M;
3586}
Bill Wendling0198ce02010-10-06 01:22:42 +00003587
Rafael Espindolad96d5532014-08-26 21:49:01 +00003588std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003589 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00003590 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolacdb871d2014-08-27 21:11:13 +00003591 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003592 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00003593 if (Triple.getError())
3594 return "";
3595 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00003596}