blob: d584015ef85cf5f7e9427d938991abb1714a5a9c [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Devang Patele4b27562009-08-28 23:24:31 +000019#include "llvm/IntrinsicInst.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000021#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000027#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000028using namespace llvm;
29
Chris Lattnerb348bb82007-05-18 04:02:46 +000030void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000031 if (BufferOwned)
32 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000033 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000034 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000035 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000036 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000037
Devang Patel19c87462008-09-26 22:53:05 +000038 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000039 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000042 MDKindMap.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000043}
44
Chris Lattner48c85b82007-05-04 03:30:17 +000045//===----------------------------------------------------------------------===//
46// Helper functions to implement forward reference resolution, etc.
47//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000048
Chris Lattnercaee0dc2007-04-22 06:23:29 +000049/// ConvertToString - Convert a string from a record into an std::string, return
50/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000051template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000052static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000053 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000054 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000055 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000056
Chris Lattner15e6d172007-05-04 19:11:41 +000057 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059 return false;
60}
61
62static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63 switch (Val) {
64 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000065 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakAnyLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceAnyLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
73 case 8: return GlobalValue::CommonLinkage;
74 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000075 case 10: return GlobalValue::WeakODRLinkage;
76 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000077 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000078 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000079 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000080 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000081 }
82}
83
84static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
85 switch (Val) {
86 default: // Map unknown visibilities to default.
87 case 0: return GlobalValue::DefaultVisibility;
88 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000089 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000090 }
91}
92
Chris Lattnerf581c3b2007-04-24 07:07:11 +000093static int GetDecodedCastOpcode(unsigned Val) {
94 switch (Val) {
95 default: return -1;
96 case bitc::CAST_TRUNC : return Instruction::Trunc;
97 case bitc::CAST_ZEXT : return Instruction::ZExt;
98 case bitc::CAST_SEXT : return Instruction::SExt;
99 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
100 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
101 case bitc::CAST_UITOFP : return Instruction::UIToFP;
102 case bitc::CAST_SITOFP : return Instruction::SIToFP;
103 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104 case bitc::CAST_FPEXT : return Instruction::FPExt;
105 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107 case bitc::CAST_BITCAST : return Instruction::BitCast;
108 }
109}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000110static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000111 switch (Val) {
112 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000113 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000114 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000115 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000116 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000117 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000118 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000119 case bitc::BINOP_UDIV: return Instruction::UDiv;
120 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000121 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000122 case bitc::BINOP_UREM: return Instruction::URem;
123 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000124 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000125 case bitc::BINOP_SHL: return Instruction::Shl;
126 case bitc::BINOP_LSHR: return Instruction::LShr;
127 case bitc::BINOP_ASHR: return Instruction::AShr;
128 case bitc::BINOP_AND: return Instruction::And;
129 case bitc::BINOP_OR: return Instruction::Or;
130 case bitc::BINOP_XOR: return Instruction::Xor;
131 }
132}
133
Eli Friedmanff030482011-07-28 21:48:00 +0000134static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
135 switch (Val) {
136 default: return AtomicRMWInst::BAD_BINOP;
137 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
138 case bitc::RMW_ADD: return AtomicRMWInst::Add;
139 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
140 case bitc::RMW_AND: return AtomicRMWInst::And;
141 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
142 case bitc::RMW_OR: return AtomicRMWInst::Or;
143 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
144 case bitc::RMW_MAX: return AtomicRMWInst::Max;
145 case bitc::RMW_MIN: return AtomicRMWInst::Min;
146 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
147 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
148 }
149}
150
Eli Friedman47f35132011-07-25 23:16:38 +0000151static AtomicOrdering GetDecodedOrdering(unsigned Val) {
152 switch (Val) {
153 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
154 case bitc::ORDERING_UNORDERED: return Unordered;
155 case bitc::ORDERING_MONOTONIC: return Monotonic;
156 case bitc::ORDERING_ACQUIRE: return Acquire;
157 case bitc::ORDERING_RELEASE: return Release;
158 case bitc::ORDERING_ACQREL: return AcquireRelease;
159 default: // Map unknown orderings to sequentially-consistent.
160 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
161 }
162}
163
164static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
165 switch (Val) {
166 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
167 default: // Map unknown scopes to cross-thread.
168 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
169 }
170}
171
Gabor Greifefe65362008-05-10 08:32:32 +0000172namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000173namespace {
174 /// @brief A class for maintaining the slot number definition
175 /// as a placeholder for the actual definition for forward constants defs.
176 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000177 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000178 public:
179 // allocate space for exactly one operand
180 void *operator new(size_t s) {
181 return User::operator new(s, 1);
182 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000183 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000184 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000185 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000186 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000187
Chris Lattnerea693df2008-08-21 02:34:16 +0000188 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000189 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000190 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000191 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000192 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
193 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000194
195
Gabor Greifefe65362008-05-10 08:32:32 +0000196 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000197 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000198 };
199}
200
Chris Lattner46e77402009-03-31 22:55:09 +0000201// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000202template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000203struct OperandTraits<ConstantPlaceHolder> :
204 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000205};
Gabor Greifefe65362008-05-10 08:32:32 +0000206}
207
Chris Lattner46e77402009-03-31 22:55:09 +0000208
209void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
210 if (Idx == size()) {
211 push_back(V);
212 return;
213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214
Chris Lattner46e77402009-03-31 22:55:09 +0000215 if (Idx >= size())
216 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000217
Chris Lattner46e77402009-03-31 22:55:09 +0000218 WeakVH &OldV = ValuePtrs[Idx];
219 if (OldV == 0) {
220 OldV = V;
221 return;
222 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000223
Chris Lattner46e77402009-03-31 22:55:09 +0000224 // Handle constants and non-constants (e.g. instrs) differently for
225 // efficiency.
226 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
227 ResolveConstants.push_back(std::make_pair(PHC, Idx));
228 OldV = V;
229 } else {
230 // If there was a forward reference to this value, replace it.
231 Value *PrevVal = OldV;
232 OldV->replaceAllUsesWith(V);
233 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000234 }
235}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000236
Gabor Greifefe65362008-05-10 08:32:32 +0000237
Chris Lattner522b7b12007-04-24 05:48:56 +0000238Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000239 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000240 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000241 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000242
Chris Lattner46e77402009-03-31 22:55:09 +0000243 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000244 assert(Ty == V->getType() && "Type mismatch in constant table!");
245 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000246 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000247
248 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000249 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000250 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000251 return C;
252}
253
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000254Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000255 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000256 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000257
Chris Lattner46e77402009-03-31 22:55:09 +0000258 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000259 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
260 return V;
261 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000262
Chris Lattner01ff65f2007-05-02 05:16:49 +0000263 // No type specified, must be invalid reference.
264 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000265
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000266 // Create and return a placeholder, which will later be RAUW'd.
267 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000268 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000269 return V;
270}
271
Chris Lattnerea693df2008-08-21 02:34:16 +0000272/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
273/// resolves any forward references. The idea behind this is that we sometimes
274/// get constants (such as large arrays) which reference *many* forward ref
275/// constants. Replacing each of these causes a lot of thrashing when
276/// building/reuniquing the constant. Instead of doing this, we look at all the
277/// uses and rewrite all the place holders at once for any constant that uses
278/// a placeholder.
279void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000281 // binary search.
282 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000283
Chris Lattnerea693df2008-08-21 02:34:16 +0000284 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattnerea693df2008-08-21 02:34:16 +0000286 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000287 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000288 Constant *Placeholder = ResolveConstants.back().first;
289 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnerea693df2008-08-21 02:34:16 +0000291 // Loop over all users of the placeholder, updating them to reference the
292 // new value. If they reference more than one placeholder, update them all
293 // at once.
294 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000295 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000296 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerea693df2008-08-21 02:34:16 +0000298 // If the using object isn't uniqued, just update the operands. This
299 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000300 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000301 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000302 continue;
303 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000304
Chris Lattnerea693df2008-08-21 02:34:16 +0000305 // Otherwise, we have a constant that uses the placeholder. Replace that
306 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000307 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
309 I != E; ++I) {
310 Value *NewOp;
311 if (!isa<ConstantPlaceHolder>(*I)) {
312 // Not a placeholder reference.
313 NewOp = *I;
314 } else if (*I == Placeholder) {
315 // Common case is that it just references this one placeholder.
316 NewOp = RealVal;
317 } else {
318 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000319 ResolveConstantsTy::iterator It =
320 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000321 std::pair<Constant*, unsigned>(cast<Constant>(*I),
322 0));
323 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000324 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 }
326
327 NewOps.push_back(cast<Constant>(NewOp));
328 }
329
330 // Make the new constant.
331 Constant *NewC;
332 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000333 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000334 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000335 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000336 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000337 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000338 } else {
339 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000340 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000342
Chris Lattnerea693df2008-08-21 02:34:16 +0000343 UserC->replaceAllUsesWith(NewC);
344 UserC->destroyConstant();
345 NewOps.clear();
346 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000347
Nick Lewyckycb337992009-05-10 20:57:05 +0000348 // Update all ValueHandles, they should be the only users at this point.
349 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000350 delete Placeholder;
351 }
352}
353
Devang Pateld5ac4042009-08-04 06:00:18 +0000354void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
355 if (Idx == size()) {
356 push_back(V);
357 return;
358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000359
Devang Pateld5ac4042009-08-04 06:00:18 +0000360 if (Idx >= size())
361 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Devang Pateld5ac4042009-08-04 06:00:18 +0000363 WeakVH &OldV = MDValuePtrs[Idx];
364 if (OldV == 0) {
365 OldV = V;
366 return;
367 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000368
Devang Pateld5ac4042009-08-04 06:00:18 +0000369 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000370 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000371 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000372 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000373 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
374 // value for Idx.
375 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000376}
377
378Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
379 if (Idx >= size())
380 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000381
Devang Pateld5ac4042009-08-04 06:00:18 +0000382 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000383 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000384 return V;
385 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000386
Devang Pateld5ac4042009-08-04 06:00:18 +0000387 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000388 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 MDValuePtrs[Idx] = V;
390 return V;
391}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000392
Chris Lattner1afcace2011-07-09 17:41:24 +0000393Type *BitcodeReader::getTypeByID(unsigned ID) {
394 // The type table size is always specified correctly.
395 if (ID >= TypeList.size())
396 return 0;
397
398 if (Type *Ty = TypeList[ID])
399 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattner1afcace2011-07-09 17:41:24 +0000401 // If we have a forward reference, the only possible case is when it is to a
402 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000403 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000404}
405
Chris Lattner1afcace2011-07-09 17:41:24 +0000406
Chris Lattner48c85b82007-05-04 03:30:17 +0000407//===----------------------------------------------------------------------===//
408// Functions for parsing blocks from the bitcode file
409//===----------------------------------------------------------------------===//
410
Devang Patel05988662008-09-25 21:00:45 +0000411bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000412 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000413 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000414
Devang Patel19c87462008-09-26 22:53:05 +0000415 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000416 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000417
Chris Lattner48c85b82007-05-04 03:30:17 +0000418 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000419
Devang Patel05988662008-09-25 21:00:45 +0000420 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000421
Chris Lattner48c85b82007-05-04 03:30:17 +0000422 // Read all the records.
423 while (1) {
424 unsigned Code = Stream.ReadCode();
425 if (Code == bitc::END_BLOCK) {
426 if (Stream.ReadBlockEnd())
427 return Error("Error at end of PARAMATTR block");
428 return false;
429 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000430
Chris Lattner48c85b82007-05-04 03:30:17 +0000431 if (Code == bitc::ENTER_SUBBLOCK) {
432 // No known subblocks, always skip them.
433 Stream.ReadSubBlockID();
434 if (Stream.SkipBlock())
435 return Error("Malformed block record");
436 continue;
437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000438
Chris Lattner48c85b82007-05-04 03:30:17 +0000439 if (Code == bitc::DEFINE_ABBREV) {
440 Stream.ReadAbbrevRecord();
441 continue;
442 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000443
Chris Lattner48c85b82007-05-04 03:30:17 +0000444 // Read a record.
445 Record.clear();
446 switch (Stream.ReadRecord(Code, Record)) {
447 default: // Default behavior: ignore.
448 break;
449 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
450 if (Record.size() & 1)
451 return Error("Invalid ENTRY record");
452
Chris Lattner9a6cb152008-10-05 18:22:09 +0000453 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000454 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000455 // to index ~0. Index 0 is used for return value attributes but used to be
456 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000457 Attributes RetAttribute = Attribute::None;
458 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000459 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000460 // FIXME: remove in LLVM 3.0
461 // The alignment is stored as a 16-bit raw value from bits 31--16.
462 // We shift the bits above 31 down by 11 bits.
463
464 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
465 if (Alignment && !isPowerOf2_32(Alignment))
466 return Error("Alignment is not a power of two.");
467
468 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
469 if (Alignment)
470 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
471 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
472 Record[i+1] = ReconstitutedAttr;
473
Devang Patel19c87462008-09-26 22:53:05 +0000474 if (Record[i] == 0)
475 RetAttribute = Record[i+1];
476 else if (Record[i] == ~0U)
477 FnAttribute = Record[i+1];
478 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000479
480 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
481 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000482
Chris Lattner9a6cb152008-10-05 18:22:09 +0000483 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
484 (RetAttribute & OldRetAttrs) != 0) {
485 if (FnAttribute == Attribute::None) { // add a slot so they get added.
486 Record.push_back(~0U);
487 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000488 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000489
Chris Lattner9a6cb152008-10-05 18:22:09 +0000490 FnAttribute |= RetAttribute & OldRetAttrs;
491 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000492 }
Chris Lattner461edd92008-03-12 02:25:52 +0000493
Devang Patel19c87462008-09-26 22:53:05 +0000494 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000495 if (Record[i] == 0) {
496 if (RetAttribute != Attribute::None)
497 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
498 } else if (Record[i] == ~0U) {
499 if (FnAttribute != Attribute::None)
500 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
501 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000502 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
503 }
Devang Patel19c87462008-09-26 22:53:05 +0000504
505 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000506 Attrs.clear();
507 break;
508 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000509 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000510 }
511}
512
Chris Lattner86697142007-05-01 05:01:34 +0000513bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000514 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000515 return Error("Malformed block record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000516
517 return ParseTypeTableBody();
518}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000519
Chris Lattner1afcace2011-07-09 17:41:24 +0000520bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000521 if (!TypeList.empty())
522 return Error("Multiple TYPE_BLOCKs found!");
523
524 SmallVector<uint64_t, 64> Record;
525 unsigned NumRecords = 0;
526
Chris Lattner1afcace2011-07-09 17:41:24 +0000527 SmallString<64> TypeName;
528
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000529 // Read all the records for this type table.
530 while (1) {
531 unsigned Code = Stream.ReadCode();
532 if (Code == bitc::END_BLOCK) {
533 if (NumRecords != TypeList.size())
534 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000535 if (Stream.ReadBlockEnd())
536 return Error("Error at end of type table block");
537 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000539
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000540 if (Code == bitc::ENTER_SUBBLOCK) {
541 // No known subblocks, always skip them.
542 Stream.ReadSubBlockID();
543 if (Stream.SkipBlock())
544 return Error("Malformed block record");
545 continue;
546 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000547
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000548 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000549 Stream.ReadAbbrevRecord();
550 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000551 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000552
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000553 // Read a record.
554 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000555 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000557 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
559 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
560 // type list. This allows us to reserve space.
561 if (Record.size() < 1)
562 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000563 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000564 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000565 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000567 break;
568 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000569 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000570 break;
571 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000572 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000573 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000574 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000575 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000576 break;
577 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000578 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000579 break;
580 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000581 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000582 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000584 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000585 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000586 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000587 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000588 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000589 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
590 ResultTy = Type::getX86_MMXTy(Context);
591 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000592 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
593 if (Record.size() < 1)
594 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000595
Owen Anderson1d0be152009-08-13 21:58:54 +0000596 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000597 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000598 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000599 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000600 if (Record.size() < 1)
601 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000602 unsigned AddressSpace = 0;
603 if (Record.size() == 2)
604 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000605 ResultTy = getTypeByID(Record[0]);
606 if (ResultTy == 0) return Error("invalid element type in pointer type");
607 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000608 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000609 }
Chad Rosiercde54642011-11-03 00:14:01 +0000610 case bitc::TYPE_CODE_FUNCTION_OLD: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000611 // FIXME: attrid is dead, remove it in LLVM 3.0
612 // FUNCTION: [vararg, attrid, retty, paramty x N]
613 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000614 return Error("Invalid FUNCTION type record");
Jay Foad5fdd6c82011-07-12 14:06:48 +0000615 std::vector<Type*> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000616 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
617 if (Type *T = getTypeByID(Record[i]))
618 ArgTys.push_back(T);
619 else
620 break;
621 }
622
623 ResultTy = getTypeByID(Record[2]);
624 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
625 return Error("invalid type in function type");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000626
Chris Lattner1afcace2011-07-09 17:41:24 +0000627 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000628 break;
629 }
Chad Rosiercde54642011-11-03 00:14:01 +0000630 case bitc::TYPE_CODE_FUNCTION: {
631 // FUNCTION: [vararg, retty, paramty x N]
632 if (Record.size() < 2)
633 return Error("Invalid FUNCTION type record");
634 std::vector<Type*> ArgTys;
635 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
636 if (Type *T = getTypeByID(Record[i]))
637 ArgTys.push_back(T);
638 else
639 break;
640 }
641
642 ResultTy = getTypeByID(Record[1]);
643 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
644 return Error("invalid type in function type");
645
646 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
647 break;
648 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000649 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000650 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000651 return Error("Invalid STRUCT type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000652 std::vector<Type*> EltTys;
653 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
654 if (Type *T = getTypeByID(Record[i]))
655 EltTys.push_back(T);
656 else
657 break;
658 }
659 if (EltTys.size() != Record.size()-1)
660 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000661 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000662 break;
663 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000664 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
665 if (ConvertToString(Record, 0, TypeName))
666 return Error("Invalid STRUCT_NAME record");
667 continue;
668
669 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
670 if (Record.size() < 1)
671 return Error("Invalid STRUCT type record");
672
673 if (NumRecords >= TypeList.size())
674 return Error("invalid TYPE table");
675
676 // Check to see if this was forward referenced, if so fill in the temp.
677 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
678 if (Res) {
679 Res->setName(TypeName);
680 TypeList[NumRecords] = 0;
681 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000682 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000683 TypeName.clear();
684
685 SmallVector<Type*, 8> EltTys;
686 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
687 if (Type *T = getTypeByID(Record[i]))
688 EltTys.push_back(T);
689 else
690 break;
691 }
692 if (EltTys.size() != Record.size()-1)
693 return Error("invalid STRUCT type record");
694 Res->setBody(EltTys, Record[0]);
695 ResultTy = Res;
696 break;
697 }
698 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
699 if (Record.size() != 1)
700 return Error("Invalid OPAQUE type record");
701
702 if (NumRecords >= TypeList.size())
703 return Error("invalid TYPE table");
704
705 // Check to see if this was forward referenced, if so fill in the temp.
706 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
707 if (Res) {
708 Res->setName(TypeName);
709 TypeList[NumRecords] = 0;
710 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000711 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000712 TypeName.clear();
713 ResultTy = Res;
714 break;
715 }
716 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
717 if (Record.size() < 2)
718 return Error("Invalid ARRAY type record");
719 if ((ResultTy = getTypeByID(Record[1])))
720 ResultTy = ArrayType::get(ResultTy, Record[0]);
721 else
722 return Error("Invalid ARRAY type element");
723 break;
724 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
725 if (Record.size() < 2)
726 return Error("Invalid VECTOR type record");
727 if ((ResultTy = getTypeByID(Record[1])))
728 ResultTy = VectorType::get(ResultTy, Record[0]);
729 else
730 return Error("Invalid ARRAY type element");
731 break;
732 }
733
734 if (NumRecords >= TypeList.size())
735 return Error("invalid TYPE table");
736 assert(ResultTy && "Didn't read a type?");
737 assert(TypeList[NumRecords] == 0 && "Already read type?");
738 TypeList[NumRecords++] = ResultTy;
739 }
740}
741
Chris Lattner86697142007-05-01 05:01:34 +0000742bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000743 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000744 return Error("Malformed block record");
745
746 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000747
Chris Lattner0b2482a2007-04-23 21:26:05 +0000748 // Read all the records for this value table.
749 SmallString<128> ValueName;
750 while (1) {
751 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000752 if (Code == bitc::END_BLOCK) {
753 if (Stream.ReadBlockEnd())
754 return Error("Error at end of value symbol table block");
755 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000756 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000757 if (Code == bitc::ENTER_SUBBLOCK) {
758 // No known subblocks, always skip them.
759 Stream.ReadSubBlockID();
760 if (Stream.SkipBlock())
761 return Error("Malformed block record");
762 continue;
763 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000764
Chris Lattner0b2482a2007-04-23 21:26:05 +0000765 if (Code == bitc::DEFINE_ABBREV) {
766 Stream.ReadAbbrevRecord();
767 continue;
768 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000769
Chris Lattner0b2482a2007-04-23 21:26:05 +0000770 // Read a record.
771 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000772 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000773 default: // Default behavior: unknown type.
774 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000775 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000776 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000777 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000778 unsigned ValueID = Record[0];
779 if (ValueID >= ValueList.size())
780 return Error("Invalid Value ID in VST_ENTRY record");
781 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000782
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000783 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000784 ValueName.clear();
785 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000786 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000787 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000788 if (ConvertToString(Record, 1, ValueName))
789 return Error("Invalid VST_BBENTRY record");
790 BasicBlock *BB = getBasicBlock(Record[0]);
791 if (BB == 0)
792 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000794 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000795 ValueName.clear();
796 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000797 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000798 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000799 }
800}
801
Devang Patele54abc92009-07-22 17:43:22 +0000802bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000803 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000804
805 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
806 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Devang Patele54abc92009-07-22 17:43:22 +0000808 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000809
Devang Patele54abc92009-07-22 17:43:22 +0000810 // Read all the records.
811 while (1) {
812 unsigned Code = Stream.ReadCode();
813 if (Code == bitc::END_BLOCK) {
814 if (Stream.ReadBlockEnd())
815 return Error("Error at end of PARAMATTR block");
816 return false;
817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000818
Devang Patele54abc92009-07-22 17:43:22 +0000819 if (Code == bitc::ENTER_SUBBLOCK) {
820 // No known subblocks, always skip them.
821 Stream.ReadSubBlockID();
822 if (Stream.SkipBlock())
823 return Error("Malformed block record");
824 continue;
825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000826
Devang Patele54abc92009-07-22 17:43:22 +0000827 if (Code == bitc::DEFINE_ABBREV) {
828 Stream.ReadAbbrevRecord();
829 continue;
830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000831
Victor Hernandez24e64df2010-01-10 07:14:18 +0000832 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000833 // Read a record.
834 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000835 Code = Stream.ReadRecord(Code, Record);
836 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000837 default: // Default behavior: ignore.
838 break;
Devang Patelaa993142009-07-29 22:34:41 +0000839 case bitc::METADATA_NAME: {
840 // Read named of the named metadata.
841 unsigned NameLength = Record.size();
842 SmallString<8> Name;
843 Name.resize(NameLength);
844 for (unsigned i = 0; i != NameLength; ++i)
845 Name[i] = Record[i];
846 Record.clear();
847 Code = Stream.ReadCode();
848
Chris Lattner9d61dd92011-06-17 17:50:30 +0000849 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000850 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000851 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000852
853 // Read named metadata elements.
854 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000855 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000856 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000857 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
858 if (MD == 0)
859 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000860 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000861 }
Devang Patelaa993142009-07-29 22:34:41 +0000862 break;
863 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000864 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000865 IsFunctionLocal = true;
866 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000867 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000868 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000869 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000870
Devang Patel104cf9e2009-07-23 01:07:34 +0000871 unsigned Size = Record.size();
872 SmallVector<Value*, 8> Elts;
873 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000874 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000875 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000876 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000877 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000878 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000879 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
880 else
881 Elts.push_back(NULL);
882 }
Jay Foadec9186b2011-04-21 19:59:31 +0000883 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000884 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000885 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000886 break;
887 }
Devang Patele54abc92009-07-22 17:43:22 +0000888 case bitc::METADATA_STRING: {
889 unsigned MDStringLength = Record.size();
890 SmallString<8> String;
891 String.resize(MDStringLength);
892 for (unsigned i = 0; i != MDStringLength; ++i)
893 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000894 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000895 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000896 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000897 break;
898 }
Devang Patele8e02132009-09-18 19:26:43 +0000899 case bitc::METADATA_KIND: {
900 unsigned RecordLength = Record.size();
901 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000902 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000903 SmallString<8> Name;
904 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000905 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000906 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000907 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000908
Chris Lattner08113472009-12-29 09:01:33 +0000909 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000910 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
911 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000912 break;
913 }
Devang Patele54abc92009-07-22 17:43:22 +0000914 }
915 }
916}
917
Chris Lattner0eef0802007-04-24 04:04:35 +0000918/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
919/// the LSB for dense VBR encoding.
920static uint64_t DecodeSignRotatedValue(uint64_t V) {
921 if ((V & 1) == 0)
922 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000923 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000924 return -(V >> 1);
925 // There is no such thing as -0 with integers. "-0" really means MININT.
926 return 1ULL << 63;
927}
928
Chris Lattner07d98b42007-04-26 02:46:40 +0000929/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
930/// values and aliases that we can.
931bool BitcodeReader::ResolveGlobalAndAliasInits() {
932 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
933 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000934
Chris Lattner07d98b42007-04-26 02:46:40 +0000935 GlobalInitWorklist.swap(GlobalInits);
936 AliasInitWorklist.swap(AliasInits);
937
938 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000939 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000940 if (ValID >= ValueList.size()) {
941 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000942 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000943 } else {
944 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
945 GlobalInitWorklist.back().first->setInitializer(C);
946 else
947 return Error("Global variable initializer is not a constant!");
948 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000949 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000950 }
951
952 while (!AliasInitWorklist.empty()) {
953 unsigned ValID = AliasInitWorklist.back().second;
954 if (ValID >= ValueList.size()) {
955 AliasInits.push_back(AliasInitWorklist.back());
956 } else {
957 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000958 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000959 else
960 return Error("Alias initializer is not a constant!");
961 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000963 }
964 return false;
965}
966
Chris Lattner86697142007-05-01 05:01:34 +0000967bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000968 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000969 return Error("Malformed block record");
970
971 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Chris Lattnere16504e2007-04-24 03:30:34 +0000973 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000974 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000975 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000976 while (1) {
977 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000978 if (Code == bitc::END_BLOCK)
979 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000980
Chris Lattnere16504e2007-04-24 03:30:34 +0000981 if (Code == bitc::ENTER_SUBBLOCK) {
982 // No known subblocks, always skip them.
983 Stream.ReadSubBlockID();
984 if (Stream.SkipBlock())
985 return Error("Malformed block record");
986 continue;
987 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000988
Chris Lattnere16504e2007-04-24 03:30:34 +0000989 if (Code == bitc::DEFINE_ABBREV) {
990 Stream.ReadAbbrevRecord();
991 continue;
992 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000993
Chris Lattnere16504e2007-04-24 03:30:34 +0000994 // Read a record.
995 Record.clear();
996 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000997 unsigned BitCode = Stream.ReadRecord(Code, Record);
998 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000999 default: // Default behavior: unknown constant
1000 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001001 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001002 break;
1003 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1004 if (Record.empty())
1005 return Error("Malformed CST_SETTYPE record");
1006 if (Record[0] >= TypeList.size())
1007 return Error("Invalid Type ID in CST_SETTYPE record");
1008 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001009 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001010 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001011 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001012 break;
1013 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001014 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001015 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001016 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001017 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001018 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001019 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001020 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001021
Chris Lattner15e6d172007-05-04 19:11:41 +00001022 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +00001023 SmallVector<uint64_t, 8> Words;
1024 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +00001025 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001026 Words[i] = DecodeSignRotatedValue(Record[i]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001027 V = ConstantInt::get(Context,
Owen Andersoneed707b2009-07-24 23:12:02 +00001028 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001029 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +00001030 break;
1031 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001032 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001033 if (Record.empty())
1034 return Error("Invalid FLOAT record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001035 if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001036 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001037 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001038 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001039 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001040 // Bits are not stored the same way as a normal i80 APInt, compensate.
1041 uint64_t Rearrange[2];
1042 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1043 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001044 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001045 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001046 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001047 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001048 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001049 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001050 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001051 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001052 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001053
Chris Lattner15e6d172007-05-04 19:11:41 +00001054 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1055 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001056 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001057
Chris Lattner15e6d172007-05-04 19:11:41 +00001058 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +00001059 std::vector<Constant*> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001060
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001061 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001062 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001063 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001064 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001065 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001066 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1067 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001068 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001069 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001070 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001071 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1072 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001073 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001074 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001075 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001076 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001077 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001078 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001079 break;
1080 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001081 case bitc::CST_CODE_STRING: { // STRING: [values]
1082 if (Record.empty())
1083 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001084
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001085 ArrayType *ATy = cast<ArrayType>(CurTy);
1086 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001087
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001088 unsigned Size = Record.size();
1089 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001090 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001091 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +00001092 V = ConstantArray::get(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001093 break;
1094 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001095 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1096 if (Record.empty())
1097 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001098
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001099 ArrayType *ATy = cast<ArrayType>(CurTy);
1100 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001101
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001102 unsigned Size = Record.size();
1103 std::vector<Constant*> Elts;
1104 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001105 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Andersona7235ea2009-07-31 20:28:14 +00001106 Elts.push_back(Constant::getNullValue(EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001107 V = ConstantArray::get(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001108 break;
1109 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001110 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1111 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1112 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001113 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001114 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001115 } else {
1116 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1117 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001118 unsigned Flags = 0;
1119 if (Record.size() >= 4) {
1120 if (Opc == Instruction::Add ||
1121 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001122 Opc == Instruction::Mul ||
1123 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001124 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1125 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1126 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1127 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001128 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001129 Opc == Instruction::UDiv ||
1130 Opc == Instruction::LShr ||
1131 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001132 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001133 Flags |= SDivOperator::IsExact;
1134 }
1135 }
1136 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001137 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001138 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001139 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001140 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1141 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1142 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001143 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001144 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001145 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001146 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001147 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001148 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001149 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001150 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001151 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001152 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001153 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001154 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001155 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001156 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001157 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001158 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001159 if (!ElTy) return Error("Invalid CE_GEP record");
1160 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1161 }
Jay Foaddab3d292011-07-21 14:31:17 +00001162 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001163 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1164 BitCode ==
1165 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001166 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001167 }
1168 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1169 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001170 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001171 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001172 ValueList.getConstantFwdRef(Record[1],CurTy),
1173 ValueList.getConstantFwdRef(Record[2],CurTy));
1174 break;
1175 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1176 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001177 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001178 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1179 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1180 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001181 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001182 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001183 break;
1184 }
1185 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001186 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001187 if (Record.size() < 3 || OpTy == 0)
1188 return Error("Invalid CE_INSERTELT record");
1189 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1190 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1191 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001192 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001193 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001194 break;
1195 }
1196 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001197 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001198 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001199 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001200 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1201 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001202 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001203 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001204 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001205 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001206 break;
1207 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001208 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001209 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1210 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001211 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001212 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1213 return Error("Invalid CE_SHUFVEC_EX record");
1214 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1215 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001216 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001217 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001218 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001219 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001220 break;
1221 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001222 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1223 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001224 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001225 if (OpTy == 0) return Error("Invalid CE_CMP record");
1226 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1227 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1228
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001229 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001230 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001231 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001232 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001233 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001234 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001235 case bitc::CST_CODE_INLINEASM: {
1236 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1237 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001238 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001239 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001240 unsigned AsmStrSize = Record[1];
1241 if (2+AsmStrSize >= Record.size())
1242 return Error("Invalid INLINEASM record");
1243 unsigned ConstStrSize = Record[2+AsmStrSize];
1244 if (3+AsmStrSize+ConstStrSize > Record.size())
1245 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001246
Chris Lattner2bce93a2007-05-06 01:58:20 +00001247 for (unsigned i = 0; i != AsmStrSize; ++i)
1248 AsmStr += (char)Record[2+i];
1249 for (unsigned i = 0; i != ConstStrSize; ++i)
1250 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001251 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001252 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001253 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001254 break;
1255 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001256 case bitc::CST_CODE_BLOCKADDRESS:{
1257 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001258 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001259 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1260 Function *Fn =
1261 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1262 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1263
1264 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1265 Type::getInt8Ty(Context),
1266 false, GlobalValue::InternalLinkage,
1267 0, "");
1268 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1269 V = FwdRef;
1270 break;
1271 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001272 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001273
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001274 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001275 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001276 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001277
Chris Lattnerea693df2008-08-21 02:34:16 +00001278 if (NextCstNo != ValueList.size())
1279 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001280
Chris Lattnerea693df2008-08-21 02:34:16 +00001281 if (Stream.ReadBlockEnd())
1282 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001283
Chris Lattnerea693df2008-08-21 02:34:16 +00001284 // Once all the constants have been read, go through and resolve forward
1285 // references.
1286 ValueList.ResolveConstantForwardRefs();
1287 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001288}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001289
Chad Rosiercbbb0962011-12-07 21:44:12 +00001290bool BitcodeReader::ParseUseLists() {
1291 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1292 return Error("Malformed block record");
1293
1294 SmallVector<uint64_t, 64> Record;
1295
1296 // Read all the records.
1297 while (1) {
1298 unsigned Code = Stream.ReadCode();
1299 if (Code == bitc::END_BLOCK) {
1300 if (Stream.ReadBlockEnd())
1301 return Error("Error at end of use-list table block");
1302 return false;
1303 }
1304
1305 if (Code == bitc::ENTER_SUBBLOCK) {
1306 // No known subblocks, always skip them.
1307 Stream.ReadSubBlockID();
1308 if (Stream.SkipBlock())
1309 return Error("Malformed block record");
1310 continue;
1311 }
1312
1313 if (Code == bitc::DEFINE_ABBREV) {
1314 Stream.ReadAbbrevRecord();
1315 continue;
1316 }
1317
1318 // Read a use list record.
1319 Record.clear();
1320 switch (Stream.ReadRecord(Code, Record)) {
1321 default: // Default behavior: unknown type.
1322 break;
1323 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1324 unsigned RecordLength = Record.size();
1325 if (RecordLength < 1)
1326 return Error ("Invalid UseList reader!");
1327 UseListRecords.push_back(Record);
1328 break;
1329 }
1330 }
1331 }
1332}
1333
Chris Lattner980e5aa2007-05-01 05:52:21 +00001334/// RememberAndSkipFunctionBody - When we see the block for a function body,
1335/// remember where it is and then skip it. This lets us lazily deserialize the
1336/// functions.
1337bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001338 // Get the function we are talking about.
1339 if (FunctionsWithBodies.empty())
1340 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001341
Chris Lattner48f84872007-05-01 04:59:48 +00001342 Function *Fn = FunctionsWithBodies.back();
1343 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001344
Chris Lattner48f84872007-05-01 04:59:48 +00001345 // Save the current stream state.
1346 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001347 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001348
Chris Lattner48f84872007-05-01 04:59:48 +00001349 // Skip over the function block for now.
1350 if (Stream.SkipBlock())
1351 return Error("Malformed block record");
1352 return false;
1353}
1354
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001355bool BitcodeReader::ParseModule() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001356 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001357 return Error("Malformed block record");
1358
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001359 SmallVector<uint64_t, 64> Record;
1360 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001361 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001362
1363 // Read all the records for this module.
1364 while (!Stream.AtEndOfStream()) {
1365 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001366 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001367 if (Stream.ReadBlockEnd())
1368 return Error("Error at end of module block");
1369
1370 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001371 ResolveGlobalAndAliasInits();
1372 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001373 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001374 if (!FunctionsWithBodies.empty())
1375 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001376
Chandler Carruth69940402007-08-04 01:51:18 +00001377 // Look for intrinsic functions which need to be upgraded at some point
1378 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1379 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001380 Function* NewFn;
1381 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001382 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1383 }
1384
Bill Wendlingde49f362010-09-10 18:51:56 +00001385 // Look for global variables which need to be renamed.
1386 for (Module::global_iterator
1387 GI = TheModule->global_begin(), GE = TheModule->global_end();
1388 GI != GE; ++GI)
1389 UpgradeGlobalVariable(GI);
1390
Chris Lattner980e5aa2007-05-01 05:52:21 +00001391 // Force deallocation of memory for these vectors to favor the client that
1392 // want lazy deserialization.
1393 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1394 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1395 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001396 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001397 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001398
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001399 if (Code == bitc::ENTER_SUBBLOCK) {
1400 switch (Stream.ReadSubBlockID()) {
1401 default: // Skip unknown content.
1402 if (Stream.SkipBlock())
1403 return Error("Malformed block record");
1404 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001405 case bitc::BLOCKINFO_BLOCK_ID:
1406 if (Stream.ReadBlockInfoBlock())
1407 return Error("Malformed BlockInfoBlock");
1408 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001409 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001410 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001411 return true;
1412 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001413 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001414 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001415 return true;
1416 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001417 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001418 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001419 return true;
1420 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001421 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001422 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001423 return true;
1424 break;
Devang Patele54abc92009-07-22 17:43:22 +00001425 case bitc::METADATA_BLOCK_ID:
1426 if (ParseMetadata())
1427 return true;
1428 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001429 case bitc::FUNCTION_BLOCK_ID:
1430 // If this is the first function body we've seen, reverse the
1431 // FunctionsWithBodies list.
1432 if (!HasReversedFunctionsWithBodies) {
1433 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1434 HasReversedFunctionsWithBodies = true;
1435 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001436
Chris Lattner980e5aa2007-05-01 05:52:21 +00001437 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001438 return true;
1439 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001440 case bitc::USELIST_BLOCK_ID:
1441 if (ParseUseLists())
1442 return true;
1443 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001444 }
1445 continue;
1446 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001447
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001448 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001449 Stream.ReadAbbrevRecord();
1450 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001451 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001452
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001453 // Read a record.
1454 switch (Stream.ReadRecord(Code, Record)) {
1455 default: break; // Default behavior, ignore unknown content.
1456 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1457 if (Record.size() < 1)
1458 return Error("Malformed MODULE_CODE_VERSION");
1459 // Only version #0 is supported so far.
1460 if (Record[0] != 0)
1461 return Error("Unknown bitstream version!");
1462 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001463 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001464 std::string S;
1465 if (ConvertToString(Record, 0, S))
1466 return Error("Invalid MODULE_CODE_TRIPLE record");
1467 TheModule->setTargetTriple(S);
1468 break;
1469 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001470 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001471 std::string S;
1472 if (ConvertToString(Record, 0, S))
1473 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1474 TheModule->setDataLayout(S);
1475 break;
1476 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001477 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001478 std::string S;
1479 if (ConvertToString(Record, 0, S))
1480 return Error("Invalid MODULE_CODE_ASM record");
1481 TheModule->setModuleInlineAsm(S);
1482 break;
1483 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001484 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001485 std::string S;
1486 if (ConvertToString(Record, 0, S))
1487 return Error("Invalid MODULE_CODE_DEPLIB record");
1488 TheModule->addLibrary(S);
1489 break;
1490 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001491 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001492 std::string S;
1493 if (ConvertToString(Record, 0, S))
1494 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1495 SectionTable.push_back(S);
1496 break;
1497 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001498 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001499 std::string S;
1500 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001501 return Error("Invalid MODULE_CODE_GCNAME record");
1502 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001503 break;
1504 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001505 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001506 // linkage, alignment, section, visibility, threadlocal,
1507 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001508 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001509 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001510 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001511 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001512 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001513 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001514 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001515 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001516 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001517
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001518 bool isConstant = Record[1];
1519 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1520 unsigned Alignment = (1 << Record[4]) >> 1;
1521 std::string Section;
1522 if (Record[5]) {
1523 if (Record[5]-1 >= SectionTable.size())
1524 return Error("Invalid section ID");
1525 Section = SectionTable[Record[5]-1];
1526 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001527 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001528 if (Record.size() > 6)
1529 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001530 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001531 if (Record.size() > 7)
1532 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001533
Rafael Espindolabea46262011-01-08 16:42:36 +00001534 bool UnnamedAddr = false;
1535 if (Record.size() > 8)
1536 UnnamedAddr = Record[8];
1537
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001538 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001539 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001540 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001541 NewGV->setAlignment(Alignment);
1542 if (!Section.empty())
1543 NewGV->setSection(Section);
1544 NewGV->setVisibility(Visibility);
1545 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001546 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001547
Chris Lattner0b2482a2007-04-23 21:26:05 +00001548 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001550 // Remember which value to use for the global initializer.
1551 if (unsigned InitID = Record[2])
1552 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001553 break;
1554 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001555 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001556 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001557 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001558 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001559 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001560 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001561 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001562 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001563 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001564 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001565 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1566 if (!FTy)
1567 return Error("Function not a pointer to function type!");
1568
Gabor Greif051a9502008-04-06 20:25:17 +00001569 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1570 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001571
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001572 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001573 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001574 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001575 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001576
Chris Lattnera9bb7132007-05-08 05:38:01 +00001577 Func->setAlignment((1 << Record[5]) >> 1);
1578 if (Record[6]) {
1579 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001580 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001581 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001582 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001583 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001584 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001585 if (Record[8]-1 > GCTable.size())
1586 return Error("Invalid GC ID");
1587 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001588 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001589 bool UnnamedAddr = false;
1590 if (Record.size() > 9)
1591 UnnamedAddr = Record[9];
1592 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001593 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594
Chris Lattner48f84872007-05-01 04:59:48 +00001595 // If this is a function with a body, remember the prototype we are
1596 // creating now, so that we can match up the body with them later.
1597 if (!isProto)
1598 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001599 break;
1600 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001601 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001602 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001603 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001604 if (Record.size() < 3)
1605 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001606 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001607 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001608 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001609 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001610
Chris Lattner07d98b42007-04-26 02:46:40 +00001611 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1612 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001613 // Old bitcode files didn't have visibility field.
1614 if (Record.size() > 3)
1615 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001616 ValueList.push_back(NewGA);
1617 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1618 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001619 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001620 /// MODULE_CODE_PURGEVALS: [numvals]
1621 case bitc::MODULE_CODE_PURGEVALS:
1622 // Trim down the value list to the specified size.
1623 if (Record.size() < 1 || Record[0] > ValueList.size())
1624 return Error("Invalid MODULE_PURGEVALS record");
1625 ValueList.shrinkTo(Record[0]);
1626 break;
1627 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001628 Record.clear();
1629 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001630
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001631 return Error("Premature end of bitstream");
1632}
1633
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001634bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001635 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001636
Chris Lattnerc453f762007-04-29 07:54:31 +00001637 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001638 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001639
Dan Gohmana4ae3a12010-04-02 00:03:51 +00001640 if (Buffer->getBufferSize() & 3) {
1641 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1642 return Error("Invalid bitcode signature");
1643 else
1644 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1645 }
1646
Chris Lattner6fa6a322008-07-09 05:14:23 +00001647 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1648 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001649 if (isBitcodeWrapper(BufPtr, BufEnd))
1650 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001651 return Error("Invalid bitcode wrapper header");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001652
Chris Lattner962dde32009-04-26 20:59:02 +00001653 StreamFile.init(BufPtr, BufEnd);
1654 Stream.init(StreamFile);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001656 // Sniff for the signature.
1657 if (Stream.Read(8) != 'B' ||
1658 Stream.Read(8) != 'C' ||
1659 Stream.Read(4) != 0x0 ||
1660 Stream.Read(4) != 0xC ||
1661 Stream.Read(4) != 0xE ||
1662 Stream.Read(4) != 0xD)
1663 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001665 // We expect a number of well-defined blocks, though we don't necessarily
1666 // need to understand them all.
1667 while (!Stream.AtEndOfStream()) {
1668 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001669
Rafael Espindolac9687b32011-05-26 18:59:54 +00001670 if (Code != bitc::ENTER_SUBBLOCK) {
1671
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001672 // The ranlib in xcode 4 will align archive members by appending newlines
1673 // to the end of them. If this file size is a multiple of 4 but not 8, we
1674 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001675 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1676 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1677 Stream.AtEndOfStream())
1678 return false;
1679
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001680 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001681 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001682
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001683 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001685 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001686 switch (BlockID) {
1687 case bitc::BLOCKINFO_BLOCK_ID:
1688 if (Stream.ReadBlockInfoBlock())
1689 return Error("Malformed BlockInfoBlock");
1690 break;
1691 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001692 // Reject multiple MODULE_BLOCK's in a single bitstream.
1693 if (TheModule)
1694 return Error("Multiple MODULE_BLOCKs in same stream");
1695 TheModule = M;
1696 if (ParseModule())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001697 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001698 break;
1699 default:
1700 if (Stream.SkipBlock())
1701 return Error("Malformed block record");
1702 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001703 }
1704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001706 return false;
1707}
Chris Lattnerc453f762007-04-29 07:54:31 +00001708
Bill Wendling34711742010-10-06 01:22:42 +00001709bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1710 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1711 return Error("Malformed block record");
1712
1713 SmallVector<uint64_t, 64> Record;
1714
1715 // Read all the records for this module.
1716 while (!Stream.AtEndOfStream()) {
1717 unsigned Code = Stream.ReadCode();
1718 if (Code == bitc::END_BLOCK) {
1719 if (Stream.ReadBlockEnd())
1720 return Error("Error at end of module block");
1721
1722 return false;
1723 }
1724
1725 if (Code == bitc::ENTER_SUBBLOCK) {
1726 switch (Stream.ReadSubBlockID()) {
1727 default: // Skip unknown content.
1728 if (Stream.SkipBlock())
1729 return Error("Malformed block record");
1730 break;
1731 }
1732 continue;
1733 }
1734
1735 if (Code == bitc::DEFINE_ABBREV) {
1736 Stream.ReadAbbrevRecord();
1737 continue;
1738 }
1739
1740 // Read a record.
1741 switch (Stream.ReadRecord(Code, Record)) {
1742 default: break; // Default behavior, ignore unknown content.
1743 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1744 if (Record.size() < 1)
1745 return Error("Malformed MODULE_CODE_VERSION");
1746 // Only version #0 is supported so far.
1747 if (Record[0] != 0)
1748 return Error("Unknown bitstream version!");
1749 break;
1750 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1751 std::string S;
1752 if (ConvertToString(Record, 0, S))
1753 return Error("Invalid MODULE_CODE_TRIPLE record");
1754 Triple = S;
1755 break;
1756 }
1757 }
1758 Record.clear();
1759 }
1760
1761 return Error("Premature end of bitstream");
1762}
1763
1764bool BitcodeReader::ParseTriple(std::string &Triple) {
1765 if (Buffer->getBufferSize() & 3)
1766 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1767
1768 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1769 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1770
1771 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1772 // The magic number is 0x0B17C0DE stored in little endian.
1773 if (isBitcodeWrapper(BufPtr, BufEnd))
1774 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1775 return Error("Invalid bitcode wrapper header");
1776
1777 StreamFile.init(BufPtr, BufEnd);
1778 Stream.init(StreamFile);
1779
1780 // Sniff for the signature.
1781 if (Stream.Read(8) != 'B' ||
1782 Stream.Read(8) != 'C' ||
1783 Stream.Read(4) != 0x0 ||
1784 Stream.Read(4) != 0xC ||
1785 Stream.Read(4) != 0xE ||
1786 Stream.Read(4) != 0xD)
1787 return Error("Invalid bitcode signature");
1788
1789 // We expect a number of well-defined blocks, though we don't necessarily
1790 // need to understand them all.
1791 while (!Stream.AtEndOfStream()) {
1792 unsigned Code = Stream.ReadCode();
1793
1794 if (Code != bitc::ENTER_SUBBLOCK)
1795 return Error("Invalid record at top-level");
1796
1797 unsigned BlockID = Stream.ReadSubBlockID();
1798
1799 // We only know the MODULE subblock ID.
1800 switch (BlockID) {
1801 case bitc::MODULE_BLOCK_ID:
1802 if (ParseModuleTriple(Triple))
1803 return true;
1804 break;
1805 default:
1806 if (Stream.SkipBlock())
1807 return Error("Malformed block record");
1808 break;
1809 }
1810 }
1811
1812 return false;
1813}
1814
Devang Patele8e02132009-09-18 19:26:43 +00001815/// ParseMetadataAttachment - Parse metadata attachments.
1816bool BitcodeReader::ParseMetadataAttachment() {
1817 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1818 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001819
Devang Patele8e02132009-09-18 19:26:43 +00001820 SmallVector<uint64_t, 64> Record;
1821 while(1) {
1822 unsigned Code = Stream.ReadCode();
1823 if (Code == bitc::END_BLOCK) {
1824 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001825 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001826 break;
1827 }
1828 if (Code == bitc::DEFINE_ABBREV) {
1829 Stream.ReadAbbrevRecord();
1830 continue;
1831 }
1832 // Read a metadata attachment record.
1833 Record.clear();
1834 switch (Stream.ReadRecord(Code, Record)) {
1835 default: // Default behavior: ignore.
1836 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001837 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001838 unsigned RecordLength = Record.size();
1839 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001840 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001841 Instruction *Inst = InstructionList[Record[0]];
1842 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001843 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001844 DenseMap<unsigned, unsigned>::iterator I =
1845 MDKindMap.find(Kind);
1846 if (I == MDKindMap.end())
1847 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001849 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001850 }
1851 break;
1852 }
1853 }
1854 }
1855 return false;
1856}
Chris Lattner48f84872007-05-01 04:59:48 +00001857
Chris Lattner980e5aa2007-05-01 05:52:21 +00001858/// ParseFunctionBody - Lazily parse the specified function body block.
1859bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001860 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001861 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Nick Lewycky9a49f152010-02-25 08:30:17 +00001863 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001864 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001865 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattner980e5aa2007-05-01 05:52:21 +00001867 // Add all the function arguments to the value table.
1868 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1869 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001871 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001872 BasicBlock *CurBB = 0;
1873 unsigned CurBBNo = 0;
1874
Chris Lattnera6245242010-04-03 02:17:50 +00001875 DebugLoc LastLoc;
1876
Chris Lattner980e5aa2007-05-01 05:52:21 +00001877 // Read all the records.
1878 SmallVector<uint64_t, 64> Record;
1879 while (1) {
1880 unsigned Code = Stream.ReadCode();
1881 if (Code == bitc::END_BLOCK) {
1882 if (Stream.ReadBlockEnd())
1883 return Error("Error at end of function block");
1884 break;
1885 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886
Chris Lattner980e5aa2007-05-01 05:52:21 +00001887 if (Code == bitc::ENTER_SUBBLOCK) {
1888 switch (Stream.ReadSubBlockID()) {
1889 default: // Skip unknown content.
1890 if (Stream.SkipBlock())
1891 return Error("Malformed block record");
1892 break;
1893 case bitc::CONSTANTS_BLOCK_ID:
1894 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001895 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001896 break;
1897 case bitc::VALUE_SYMTAB_BLOCK_ID:
1898 if (ParseValueSymbolTable()) return true;
1899 break;
Devang Patele8e02132009-09-18 19:26:43 +00001900 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001901 if (ParseMetadataAttachment()) return true;
1902 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001903 case bitc::METADATA_BLOCK_ID:
1904 if (ParseMetadata()) return true;
1905 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001906 }
1907 continue;
1908 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001909
Chris Lattner980e5aa2007-05-01 05:52:21 +00001910 if (Code == bitc::DEFINE_ABBREV) {
1911 Stream.ReadAbbrevRecord();
1912 continue;
1913 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001914
Chris Lattner980e5aa2007-05-01 05:52:21 +00001915 // Read a record.
1916 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001917 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001918 unsigned BitCode = Stream.ReadRecord(Code, Record);
1919 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001920 default: // Default behavior: reject
1921 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001922 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001923 if (Record.size() < 1 || Record[0] == 0)
1924 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001925 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001926 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001927 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001928 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001929 CurBB = FunctionBBs[0];
1930 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001931
1932 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1933 // This record indicates that the last instruction is at the same
1934 // location as the previous instruction with a location.
1935 I = 0;
1936
1937 // Get the last instruction emitted.
1938 if (CurBB && !CurBB->empty())
1939 I = &CurBB->back();
1940 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1941 !FunctionBBs[CurBBNo-1]->empty())
1942 I = &FunctionBBs[CurBBNo-1]->back();
1943
1944 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1945 I->setDebugLoc(LastLoc);
1946 I = 0;
1947 continue;
1948
Chris Lattner4f6bab92011-06-17 18:17:37 +00001949 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001950 I = 0; // Get the last instruction emitted.
1951 if (CurBB && !CurBB->empty())
1952 I = &CurBB->back();
1953 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1954 !FunctionBBs[CurBBNo-1]->empty())
1955 I = &FunctionBBs[CurBBNo-1]->back();
1956 if (I == 0 || Record.size() < 4)
1957 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1958
1959 unsigned Line = Record[0], Col = Record[1];
1960 unsigned ScopeID = Record[2], IAID = Record[3];
1961
1962 MDNode *Scope = 0, *IA = 0;
1963 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1964 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1965 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1966 I->setDebugLoc(LastLoc);
1967 I = 0;
1968 continue;
1969 }
1970
Chris Lattnerabfbf852007-05-06 00:21:25 +00001971 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1972 unsigned OpNum = 0;
1973 Value *LHS, *RHS;
1974 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1975 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001976 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001977 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001978
Dan Gohman1224c382009-07-20 21:19:07 +00001979 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001980 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001981 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001982 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001983 if (OpNum < Record.size()) {
1984 if (Opc == Instruction::Add ||
1985 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001986 Opc == Instruction::Mul ||
1987 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001988 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001989 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00001990 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001991 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00001992 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001993 Opc == Instruction::UDiv ||
1994 Opc == Instruction::LShr ||
1995 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001996 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001997 cast<BinaryOperator>(I)->setIsExact(true);
1998 }
1999 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002000 break;
2001 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002002 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2003 unsigned OpNum = 0;
2004 Value *Op;
2005 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2006 OpNum+2 != Record.size())
2007 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002009 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002010 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2011 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002012 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002013 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002014 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002015 break;
2016 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002017 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002018 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002019 unsigned OpNum = 0;
2020 Value *BasePtr;
2021 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002022 return Error("Invalid GEP record");
2023
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002024 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002025 while (OpNum != Record.size()) {
2026 Value *Op;
2027 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002028 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002029 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002030 }
2031
Jay Foada9203102011-07-25 09:48:08 +00002032 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002033 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002034 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002035 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002036 break;
2037 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002038
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002039 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2040 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002041 unsigned OpNum = 0;
2042 Value *Agg;
2043 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2044 return Error("Invalid EXTRACTVAL record");
2045
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002046 SmallVector<unsigned, 4> EXTRACTVALIdx;
2047 for (unsigned RecSize = Record.size();
2048 OpNum != RecSize; ++OpNum) {
2049 uint64_t Index = Record[OpNum];
2050 if ((unsigned)Index != Index)
2051 return Error("Invalid EXTRACTVAL index");
2052 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002053 }
2054
Jay Foadfc6d3a42011-07-13 10:26:04 +00002055 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002056 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002057 break;
2058 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002059
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002060 case bitc::FUNC_CODE_INST_INSERTVAL: {
2061 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002062 unsigned OpNum = 0;
2063 Value *Agg;
2064 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2065 return Error("Invalid INSERTVAL record");
2066 Value *Val;
2067 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2068 return Error("Invalid INSERTVAL record");
2069
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002070 SmallVector<unsigned, 4> INSERTVALIdx;
2071 for (unsigned RecSize = Record.size();
2072 OpNum != RecSize; ++OpNum) {
2073 uint64_t Index = Record[OpNum];
2074 if ((unsigned)Index != Index)
2075 return Error("Invalid INSERTVAL index");
2076 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002077 }
2078
Jay Foadfc6d3a42011-07-13 10:26:04 +00002079 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002080 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002081 break;
2082 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002083
Chris Lattnerabfbf852007-05-06 00:21:25 +00002084 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002085 // obsolete form of select
2086 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002087 unsigned OpNum = 0;
2088 Value *TrueVal, *FalseVal, *Cond;
2089 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2090 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002091 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002092 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002093
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002094 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002095 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002096 break;
2097 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002098
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002099 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2100 // new form of select
2101 // handles select i1 or select [N x i1]
2102 unsigned OpNum = 0;
2103 Value *TrueVal, *FalseVal, *Cond;
2104 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2105 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2106 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2107 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002108
2109 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002110 if (VectorType* vector_type =
2111 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002112 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002113 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002114 return Error("Invalid SELECT condition type");
2115 } else {
2116 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002117 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002118 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002119 }
2120
Gabor Greif051a9502008-04-06 20:25:17 +00002121 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002122 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002123 break;
2124 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002125
Chris Lattner01ff65f2007-05-02 05:16:49 +00002126 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002127 unsigned OpNum = 0;
2128 Value *Vec, *Idx;
2129 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002130 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002131 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002132 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002133 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002134 break;
2135 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002136
Chris Lattner01ff65f2007-05-02 05:16:49 +00002137 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002138 unsigned OpNum = 0;
2139 Value *Vec, *Elt, *Idx;
2140 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002141 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002142 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002143 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002144 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002145 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002146 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002147 break;
2148 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002149
Chris Lattnerabfbf852007-05-06 00:21:25 +00002150 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2151 unsigned OpNum = 0;
2152 Value *Vec1, *Vec2, *Mask;
2153 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2154 getValue(Record, OpNum, Vec1->getType(), Vec2))
2155 return Error("Invalid SHUFFLEVEC record");
2156
Mon P Wangaeb06d22008-11-10 04:46:22 +00002157 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002158 return Error("Invalid SHUFFLEVEC record");
2159 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002160 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002161 break;
2162 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002163
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002164 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2165 // Old form of ICmp/FCmp returning bool
2166 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2167 // both legal on vectors but had different behaviour.
2168 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2169 // FCmp/ICmp returning bool or vector of bool
2170
Chris Lattner7337ab92007-05-06 00:00:00 +00002171 unsigned OpNum = 0;
2172 Value *LHS, *RHS;
2173 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2174 getValue(Record, OpNum, LHS->getType(), RHS) ||
2175 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002176 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002177
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002178 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002179 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002180 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002181 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002182 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002183 break;
2184 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002185
Chris Lattner231cbcb2007-05-02 04:27:25 +00002186 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002187 {
2188 unsigned Size = Record.size();
2189 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002190 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002191 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002192 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002193 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002194
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002195 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002196 Value *Op = NULL;
2197 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2198 return Error("Invalid RET record");
2199 if (OpNum != Record.size())
2200 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002201
Chris Lattner96a74c52011-06-17 18:09:11 +00002202 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002203 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002204 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002205 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002206 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002207 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002208 return Error("Invalid BR record");
2209 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2210 if (TrueDest == 0)
2211 return Error("Invalid BR record");
2212
Devang Patele8e02132009-09-18 19:26:43 +00002213 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002214 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002215 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002216 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002217 else {
2218 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002219 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002220 if (FalseDest == 0 || Cond == 0)
2221 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002222 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002223 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002224 }
2225 break;
2226 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002227 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002228 if (Record.size() < 3 || (Record.size() & 1) == 0)
2229 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002230 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002231 Value *Cond = getFnValueByID(Record[1], OpTy);
2232 BasicBlock *Default = getBasicBlock(Record[2]);
2233 if (OpTy == 0 || Cond == 0 || Default == 0)
2234 return Error("Invalid SWITCH record");
2235 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002236 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002237 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002238 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002239 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002240 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2241 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2242 if (CaseVal == 0 || DestBB == 0) {
2243 delete SI;
2244 return Error("Invalid SWITCH record!");
2245 }
2246 SI->addCase(CaseVal, DestBB);
2247 }
2248 I = SI;
2249 break;
2250 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002251 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002252 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002253 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002254 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002255 Value *Address = getFnValueByID(Record[1], OpTy);
2256 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002257 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002258 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002259 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002260 InstructionList.push_back(IBI);
2261 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2262 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2263 IBI->addDestination(DestBB);
2264 } else {
2265 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002266 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002267 }
2268 }
2269 I = IBI;
2270 break;
2271 }
2272
Duncan Sandsdc024672007-11-27 13:23:08 +00002273 case bitc::FUNC_CODE_INST_INVOKE: {
2274 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002275 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002276 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002277 unsigned CCInfo = Record[1];
2278 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2279 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002280
Chris Lattnera9bb7132007-05-08 05:38:01 +00002281 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002282 Value *Callee;
2283 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002284 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002285
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002286 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2287 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002288 dyn_cast<FunctionType>(CalleeTy->getElementType());
2289
2290 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002291 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2292 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002293 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002294
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002295 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002296 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2297 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2298 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002299 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002300
Chris Lattner7337ab92007-05-06 00:00:00 +00002301 if (!FTy->isVarArg()) {
2302 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002303 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002304 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002305 // Read type/value pairs for varargs params.
2306 while (OpNum != Record.size()) {
2307 Value *Op;
2308 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2309 return Error("Invalid INVOKE record");
2310 Ops.push_back(Op);
2311 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002312 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002313
Jay Foada3efbb12011-07-15 08:37:34 +00002314 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002315 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002316 cast<InvokeInst>(I)->setCallingConv(
2317 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002318 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002319 break;
2320 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002321 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2322 unsigned Idx = 0;
2323 Value *Val = 0;
2324 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2325 return Error("Invalid RESUME record");
2326 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002327 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002328 break;
2329 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002330 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
Owen Anderson1d0be152009-08-13 21:58:54 +00002331 I = new UnwindInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002332 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002333 break;
2334 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002335 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002336 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002337 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002338 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002339 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002340 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002341 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002342 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002343
Jay Foad3ecfc862011-03-30 11:28:46 +00002344 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002345 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002346
Chris Lattner15e6d172007-05-04 19:11:41 +00002347 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2348 Value *V = getFnValueByID(Record[1+i], Ty);
2349 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002350 if (!V || !BB) return Error("Invalid PHI record");
2351 PN->addIncoming(V, BB);
2352 }
2353 I = PN;
2354 break;
2355 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002356
Bill Wendlinge6e88262011-08-12 20:24:12 +00002357 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2358 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2359 unsigned Idx = 0;
2360 if (Record.size() < 4)
2361 return Error("Invalid LANDINGPAD record");
2362 Type *Ty = getTypeByID(Record[Idx++]);
2363 if (!Ty) return Error("Invalid LANDINGPAD record");
2364 Value *PersFn = 0;
2365 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2366 return Error("Invalid LANDINGPAD record");
2367
2368 bool IsCleanup = !!Record[Idx++];
2369 unsigned NumClauses = Record[Idx++];
2370 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2371 LP->setCleanup(IsCleanup);
2372 for (unsigned J = 0; J != NumClauses; ++J) {
2373 LandingPadInst::ClauseType CT =
2374 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2375 Value *Val;
2376
2377 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2378 delete LP;
2379 return Error("Invalid LANDINGPAD record");
2380 }
2381
2382 assert((CT != LandingPadInst::Catch ||
2383 !isa<ArrayType>(Val->getType())) &&
2384 "Catch clause has a invalid type!");
2385 assert((CT != LandingPadInst::Filter ||
2386 isa<ArrayType>(Val->getType())) &&
2387 "Filter clause has invalid type!");
2388 LP->addClause(Val);
2389 }
2390
2391 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002392 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002393 break;
2394 }
2395
Chris Lattner96a74c52011-06-17 18:09:11 +00002396 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2397 if (Record.size() != 4)
2398 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002399 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002400 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002401 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002402 Value *Size = getFnValueByID(Record[2], OpTy);
2403 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002404 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002405 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002406 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002407 break;
2408 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002409 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002410 unsigned OpNum = 0;
2411 Value *Op;
2412 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2413 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002414 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002415
Chris Lattner7337ab92007-05-06 00:00:00 +00002416 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002417 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002418 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002419 }
Eli Friedman21006d42011-08-09 23:02:53 +00002420 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2421 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2422 unsigned OpNum = 0;
2423 Value *Op;
2424 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2425 OpNum+4 != Record.size())
2426 return Error("Invalid LOADATOMIC record");
2427
2428
2429 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2430 if (Ordering == NotAtomic || Ordering == Release ||
2431 Ordering == AcquireRelease)
2432 return Error("Invalid LOADATOMIC record");
2433 if (Ordering != NotAtomic && Record[OpNum] == 0)
2434 return Error("Invalid LOADATOMIC record");
2435 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2436
2437 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2438 Ordering, SynchScope);
2439 InstructionList.push_back(I);
2440 break;
2441 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002442 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002443 unsigned OpNum = 0;
2444 Value *Val, *Ptr;
2445 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002446 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002447 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2448 OpNum+2 != Record.size())
2449 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002450
Christopher Lambfe63fb92007-12-11 08:59:05 +00002451 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002452 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002453 break;
2454 }
Eli Friedman21006d42011-08-09 23:02:53 +00002455 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2456 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2457 unsigned OpNum = 0;
2458 Value *Val, *Ptr;
2459 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2460 getValue(Record, OpNum,
2461 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2462 OpNum+4 != Record.size())
2463 return Error("Invalid STOREATOMIC record");
2464
2465 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002466 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002467 Ordering == AcquireRelease)
2468 return Error("Invalid STOREATOMIC record");
2469 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2470 if (Ordering != NotAtomic && Record[OpNum] == 0)
2471 return Error("Invalid STOREATOMIC record");
2472
2473 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2474 Ordering, SynchScope);
2475 InstructionList.push_back(I);
2476 break;
2477 }
Eli Friedmanff030482011-07-28 21:48:00 +00002478 case bitc::FUNC_CODE_INST_CMPXCHG: {
2479 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2480 unsigned OpNum = 0;
2481 Value *Ptr, *Cmp, *New;
2482 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2483 getValue(Record, OpNum,
2484 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2485 getValue(Record, OpNum,
2486 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2487 OpNum+3 != Record.size())
2488 return Error("Invalid CMPXCHG record");
2489 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002490 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002491 return Error("Invalid CMPXCHG record");
2492 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2493 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2494 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2495 InstructionList.push_back(I);
2496 break;
2497 }
2498 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2499 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2500 unsigned OpNum = 0;
2501 Value *Ptr, *Val;
2502 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2503 getValue(Record, OpNum,
2504 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2505 OpNum+4 != Record.size())
2506 return Error("Invalid ATOMICRMW record");
2507 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2508 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2509 Operation > AtomicRMWInst::LAST_BINOP)
2510 return Error("Invalid ATOMICRMW record");
2511 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002512 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002513 return Error("Invalid ATOMICRMW record");
2514 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2515 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2516 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2517 InstructionList.push_back(I);
2518 break;
2519 }
Eli Friedman47f35132011-07-25 23:16:38 +00002520 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2521 if (2 != Record.size())
2522 return Error("Invalid FENCE record");
2523 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2524 if (Ordering == NotAtomic || Ordering == Unordered ||
2525 Ordering == Monotonic)
2526 return Error("Invalid FENCE record");
2527 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2528 I = new FenceInst(Context, Ordering, SynchScope);
2529 InstructionList.push_back(I);
2530 break;
2531 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002532 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002533 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2534 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002535 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002536
Devang Patel05988662008-09-25 21:00:45 +00002537 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002538 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002539
Chris Lattnera9bb7132007-05-08 05:38:01 +00002540 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002541 Value *Callee;
2542 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2543 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002544
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002545 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2546 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002547 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002548 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002549 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002550
Chris Lattner0579f7f2007-05-03 22:04:19 +00002551 SmallVector<Value*, 16> Args;
2552 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002553 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002554 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002555 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002556 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002557 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002558 if (Args.back() == 0) return Error("Invalid CALL record");
2559 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002560
Chris Lattner0579f7f2007-05-03 22:04:19 +00002561 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002562 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002563 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002564 return Error("Invalid CALL record");
2565 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002566 while (OpNum != Record.size()) {
2567 Value *Op;
2568 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2569 return Error("Invalid CALL record");
2570 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002571 }
2572 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002573
Jay Foada3efbb12011-07-15 08:37:34 +00002574 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002575 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002576 cast<CallInst>(I)->setCallingConv(
2577 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002578 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002579 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002580 break;
2581 }
2582 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2583 if (Record.size() < 3)
2584 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002585 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002586 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002587 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002588 if (!OpTy || !Op || !ResTy)
2589 return Error("Invalid VAARG record");
2590 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002591 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002592 break;
2593 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002594 }
2595
2596 // Add instruction to end of current BB. If there is no current BB, reject
2597 // this file.
2598 if (CurBB == 0) {
2599 delete I;
2600 return Error("Invalid instruction with no BB");
2601 }
2602 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002603
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002604 // If this was a terminator instruction, move to the next block.
2605 if (isa<TerminatorInst>(I)) {
2606 ++CurBBNo;
2607 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2608 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002609
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002610 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002611 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002612 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002613 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002614
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002615 // Check the function list for unresolved values.
2616 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2617 if (A->getParent() == 0) {
2618 // We found at least one unresolved value. Nuke them all to avoid leaks.
2619 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002620 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002621 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002622 delete A;
2623 }
2624 }
Chris Lattner35a04702007-05-04 03:50:29 +00002625 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002626 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002628
Dan Gohman064ff3e2010-08-25 20:23:38 +00002629 // FIXME: Check for unresolved forward-declared metadata references
2630 // and clean up leaks.
2631
Chris Lattner50b136d2009-10-28 05:53:48 +00002632 // See if anything took the address of blocks in this function. If so,
2633 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002634 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2635 BlockAddrFwdRefs.find(F);
2636 if (BAFRI != BlockAddrFwdRefs.end()) {
2637 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2638 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2639 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002640 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002641 return Error("Invalid blockaddress block #");
2642
2643 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002644 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002645 FwdRef->eraseFromParent();
2646 }
2647
2648 BlockAddrFwdRefs.erase(BAFRI);
2649 }
2650
Chris Lattner980e5aa2007-05-01 05:52:21 +00002651 // Trim the value list down to the size it was before we parsed this function.
2652 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002653 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002654 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002655 return false;
2656}
2657
Chris Lattnerb348bb82007-05-18 04:02:46 +00002658//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002659// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002660//===----------------------------------------------------------------------===//
2661
2662
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002663bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2664 if (const Function *F = dyn_cast<Function>(GV)) {
2665 return F->isDeclaration() &&
2666 DeferredFunctionInfo.count(const_cast<Function*>(F));
2667 }
2668 return false;
2669}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002670
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002671bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2672 Function *F = dyn_cast<Function>(GV);
2673 // If it's not a function or is already material, ignore the request.
2674 if (!F || !F->isMaterializable()) return false;
2675
2676 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002677 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002678
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002679 // Move the bit stream to the saved position of the deferred function body.
2680 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002681
Chris Lattnerb348bb82007-05-18 04:02:46 +00002682 if (ParseFunctionBody(F)) {
2683 if (ErrInfo) *ErrInfo = ErrorString;
2684 return true;
2685 }
Chandler Carruth69940402007-08-04 01:51:18 +00002686
2687 // Upgrade any old intrinsic calls in the function.
2688 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2689 E = UpgradedIntrinsics.end(); I != E; ++I) {
2690 if (I->first != I->second) {
2691 for (Value::use_iterator UI = I->first->use_begin(),
2692 UE = I->first->use_end(); UI != UE; ) {
2693 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2694 UpgradeIntrinsicCall(CI, I->second);
2695 }
2696 }
2697 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002698
Chris Lattnerb348bb82007-05-18 04:02:46 +00002699 return false;
2700}
2701
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002702bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2703 const Function *F = dyn_cast<Function>(GV);
2704 if (!F || F->isDeclaration())
2705 return false;
2706 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2707}
2708
2709void BitcodeReader::Dematerialize(GlobalValue *GV) {
2710 Function *F = dyn_cast<Function>(GV);
2711 // If this function isn't dematerializable, this is a noop.
2712 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002713 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002714
Chris Lattnerb348bb82007-05-18 04:02:46 +00002715 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002716
Chris Lattnerb348bb82007-05-18 04:02:46 +00002717 // Just forget the function body, we can remat it later.
2718 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002719}
2720
2721
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002722bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2723 assert(M == TheModule &&
2724 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002725 // Iterate over the module, deserializing any functions that are still on
2726 // disk.
2727 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2728 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002729 if (F->isMaterializable() &&
2730 Materialize(F, ErrInfo))
2731 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002732
Daniel Dunbara279bc32009-09-20 02:20:51 +00002733 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2734 // delete the old functions to clean up. We can't do this unless the entire
2735 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002736 // with calls to the old function.
2737 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2738 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2739 if (I->first != I->second) {
2740 for (Value::use_iterator UI = I->first->use_begin(),
2741 UE = I->first->use_end(); UI != UE; ) {
2742 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2743 UpgradeIntrinsicCall(CI, I->second);
2744 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002745 if (!I->first->use_empty())
2746 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002747 I->first->eraseFromParent();
2748 }
2749 }
2750 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002751
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002752 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002753}
2754
Chris Lattner48f84872007-05-01 04:59:48 +00002755
Chris Lattnerc453f762007-04-29 07:54:31 +00002756//===----------------------------------------------------------------------===//
2757// External interface
2758//===----------------------------------------------------------------------===//
2759
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002760/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002761///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002762Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2763 LLVMContext& Context,
2764 std::string *ErrMsg) {
2765 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002766 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002767 M->setMaterializer(R);
2768 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002769 if (ErrMsg)
2770 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002771
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002772 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002773 return 0;
2774 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002775 // Have the BitcodeReader dtor delete 'Buffer'.
2776 R->setBufferOwned(true);
2777 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002778}
2779
2780/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2781/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002782Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002783 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002784 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2785 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002786
2787 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2788 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002789 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002790
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002791 // Read in the entire module, and destroy the BitcodeReader.
2792 if (M->MaterializeAllPermanently(ErrMsg)) {
2793 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002794 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002795 }
Bill Wendling34711742010-10-06 01:22:42 +00002796
Chad Rosiercbbb0962011-12-07 21:44:12 +00002797 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2798 // written. We must defer until the Module has been fully materialized.
2799
Chris Lattnerc453f762007-04-29 07:54:31 +00002800 return M;
2801}
Bill Wendling34711742010-10-06 01:22:42 +00002802
2803std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2804 LLVMContext& Context,
2805 std::string *ErrMsg) {
2806 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2807 // Don't let the BitcodeReader dtor delete 'Buffer'.
2808 R->setBufferOwned(false);
2809
2810 std::string Triple("");
2811 if (R->ParseTriple(Triple))
2812 if (ErrMsg)
2813 *ErrMsg = R->getErrorString();
2814
2815 delete R;
2816 return Triple;
2817}