blob: dd9db8f4366f479a15bd64b8b8a6bad365eb5cdd [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"
Chris Lattnera7c49aa2007-05-01 07:01:57 +000019#include "llvm/Instructions.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Chandler Carruth69940402007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000022#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000023#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000026#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000027using namespace llvm;
28
Chris Lattnerb348bb82007-05-18 04:02:46 +000029void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000030 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000031 Buffer = 0;
32 std::vector<PATypeHolder>().swap(TypeList);
33 ValueList.clear();
Chris Lattner461edd92008-03-12 02:25:52 +000034
Devang Patel19c87462008-09-26 22:53:05 +000035 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000036 std::vector<BasicBlock*>().swap(FunctionBBs);
37 std::vector<Function*>().swap(FunctionsWithBodies);
38 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000039}
40
Chris Lattner48c85b82007-05-04 03:30:17 +000041//===----------------------------------------------------------------------===//
42// Helper functions to implement forward reference resolution, etc.
43//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000044
Chris Lattnercaee0dc2007-04-22 06:23:29 +000045/// ConvertToString - Convert a string from a record into an std::string, return
46/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000047template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000048static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000049 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000050 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000051 return true;
52
Chris Lattner15e6d172007-05-04 19:11:41 +000053 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000055 return false;
56}
57
58static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
59 switch (Val) {
60 default: // Map unknown/new linkages to external
61 case 0: return GlobalValue::ExternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000062 case 1: return GlobalValue::WeakAnyLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063 case 2: return GlobalValue::AppendingLinkage;
64 case 3: return GlobalValue::InternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000065 case 4: return GlobalValue::LinkOnceAnyLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000066 case 5: return GlobalValue::DLLImportLinkage;
67 case 6: return GlobalValue::DLLExportLinkage;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +000068 case 7: return GlobalValue::ExternalWeakLinkage;
Duncan Sands4dc2b392009-03-11 20:14:15 +000069 case 8: return GlobalValue::CommonLinkage;
Rafael Espindolabb46f522009-01-15 20:18:42 +000070 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000071 case 10: return GlobalValue::WeakODRLinkage;
72 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000073 }
74}
75
76static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
77 switch (Val) {
78 default: // Map unknown visibilities to default.
79 case 0: return GlobalValue::DefaultVisibility;
80 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000081 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000082 }
83}
84
Chris Lattnerf581c3b2007-04-24 07:07:11 +000085static int GetDecodedCastOpcode(unsigned Val) {
86 switch (Val) {
87 default: return -1;
88 case bitc::CAST_TRUNC : return Instruction::Trunc;
89 case bitc::CAST_ZEXT : return Instruction::ZExt;
90 case bitc::CAST_SEXT : return Instruction::SExt;
91 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
92 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
93 case bitc::CAST_UITOFP : return Instruction::UIToFP;
94 case bitc::CAST_SITOFP : return Instruction::SIToFP;
95 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
96 case bitc::CAST_FPEXT : return Instruction::FPExt;
97 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
98 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
99 case bitc::CAST_BITCAST : return Instruction::BitCast;
100 }
101}
102static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
103 switch (Val) {
104 default: return -1;
105 case bitc::BINOP_ADD: return Instruction::Add;
106 case bitc::BINOP_SUB: return Instruction::Sub;
107 case bitc::BINOP_MUL: return Instruction::Mul;
108 case bitc::BINOP_UDIV: return Instruction::UDiv;
109 case bitc::BINOP_SDIV:
110 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
111 case bitc::BINOP_UREM: return Instruction::URem;
112 case bitc::BINOP_SREM:
113 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
114 case bitc::BINOP_SHL: return Instruction::Shl;
115 case bitc::BINOP_LSHR: return Instruction::LShr;
116 case bitc::BINOP_ASHR: return Instruction::AShr;
117 case bitc::BINOP_AND: return Instruction::And;
118 case bitc::BINOP_OR: return Instruction::Or;
119 case bitc::BINOP_XOR: return Instruction::Xor;
120 }
121}
122
Gabor Greifefe65362008-05-10 08:32:32 +0000123namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000124namespace {
125 /// @brief A class for maintaining the slot number definition
126 /// as a placeholder for the actual definition for forward constants defs.
127 class ConstantPlaceHolder : public ConstantExpr {
128 ConstantPlaceHolder(); // DO NOT IMPLEMENT
129 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000130 public:
131 // allocate space for exactly one operand
132 void *operator new(size_t s) {
133 return User::operator new(s, 1);
134 }
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000135 explicit ConstantPlaceHolder(const Type *Ty)
Gabor Greifefe65362008-05-10 08:32:32 +0000136 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
137 Op<0>() = UndefValue::get(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000138 }
Chris Lattnerea693df2008-08-21 02:34:16 +0000139
140 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
141 static inline bool classof(const ConstantPlaceHolder *) { return true; }
142 static bool classof(const Value *V) {
143 return isa<ConstantExpr>(V) &&
144 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
145 }
146
147
Gabor Greifefe65362008-05-10 08:32:32 +0000148 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000149 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000150 };
151}
152
Chris Lattner46e77402009-03-31 22:55:09 +0000153// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000154template <>
155struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
156};
Gabor Greifefe65362008-05-10 08:32:32 +0000157}
158
Chris Lattner46e77402009-03-31 22:55:09 +0000159
160void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
161 if (Idx == size()) {
162 push_back(V);
163 return;
164 }
165
166 if (Idx >= size())
167 resize(Idx+1);
168
169 WeakVH &OldV = ValuePtrs[Idx];
170 if (OldV == 0) {
171 OldV = V;
172 return;
173 }
174
175 // Handle constants and non-constants (e.g. instrs) differently for
176 // efficiency.
177 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
178 ResolveConstants.push_back(std::make_pair(PHC, Idx));
179 OldV = V;
180 } else {
181 // If there was a forward reference to this value, replace it.
182 Value *PrevVal = OldV;
183 OldV->replaceAllUsesWith(V);
184 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000185 }
186}
Chris Lattner46e77402009-03-31 22:55:09 +0000187
Gabor Greifefe65362008-05-10 08:32:32 +0000188
Chris Lattner522b7b12007-04-24 05:48:56 +0000189Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
190 const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000191 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000192 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000193
Chris Lattner46e77402009-03-31 22:55:09 +0000194 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000195 assert(Ty == V->getType() && "Type mismatch in constant table!");
196 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000197 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000198
199 // Create and return a placeholder, which will later be RAUW'd.
200 Constant *C = new ConstantPlaceHolder(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000201 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000202 return C;
203}
204
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000205Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000206 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000207 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000208
Chris Lattner46e77402009-03-31 22:55:09 +0000209 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000210 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
211 return V;
212 }
213
Chris Lattner01ff65f2007-05-02 05:16:49 +0000214 // No type specified, must be invalid reference.
215 if (Ty == 0) return 0;
216
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000217 // Create and return a placeholder, which will later be RAUW'd.
218 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000219 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000220 return V;
221}
222
Chris Lattnerea693df2008-08-21 02:34:16 +0000223/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
224/// resolves any forward references. The idea behind this is that we sometimes
225/// get constants (such as large arrays) which reference *many* forward ref
226/// constants. Replacing each of these causes a lot of thrashing when
227/// building/reuniquing the constant. Instead of doing this, we look at all the
228/// uses and rewrite all the place holders at once for any constant that uses
229/// a placeholder.
230void BitcodeReaderValueList::ResolveConstantForwardRefs() {
231 // Sort the values by-pointer so that they are efficient to look up with a
232 // binary search.
233 std::sort(ResolveConstants.begin(), ResolveConstants.end());
234
235 SmallVector<Constant*, 64> NewOps;
236
237 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000238 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000239 Constant *Placeholder = ResolveConstants.back().first;
240 ResolveConstants.pop_back();
241
242 // Loop over all users of the placeholder, updating them to reference the
243 // new value. If they reference more than one placeholder, update them all
244 // at once.
245 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000246 Value::use_iterator UI = Placeholder->use_begin();
247
Chris Lattnerea693df2008-08-21 02:34:16 +0000248 // If the using object isn't uniqued, just update the operands. This
249 // handles instructions and initializers for global variables.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000250 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
251 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000252 continue;
253 }
254
255 // Otherwise, we have a constant that uses the placeholder. Replace that
256 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000257 Constant *UserC = cast<Constant>(*UI);
Chris Lattnerea693df2008-08-21 02:34:16 +0000258 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
259 I != E; ++I) {
260 Value *NewOp;
261 if (!isa<ConstantPlaceHolder>(*I)) {
262 // Not a placeholder reference.
263 NewOp = *I;
264 } else if (*I == Placeholder) {
265 // Common case is that it just references this one placeholder.
266 NewOp = RealVal;
267 } else {
268 // Otherwise, look up the placeholder in ResolveConstants.
269 ResolveConstantsTy::iterator It =
270 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
271 std::pair<Constant*, unsigned>(cast<Constant>(*I),
272 0));
273 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000274 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000275 }
276
277 NewOps.push_back(cast<Constant>(NewOp));
278 }
279
280 // Make the new constant.
281 Constant *NewC;
282 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
283 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
284 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
285 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
286 UserCS->getType()->isPacked());
287 } else if (isa<ConstantVector>(UserC)) {
288 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
289 } else {
290 // Must be a constant expression.
291 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
292 NewOps.size());
293 }
294
295 UserC->replaceAllUsesWith(NewC);
296 UserC->destroyConstant();
297 NewOps.clear();
298 }
299
300 delete Placeholder;
301 }
302}
303
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000304
305const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
306 // If the TypeID is in range, return it.
307 if (ID < TypeList.size())
308 return TypeList[ID].get();
309 if (!isTypeTable) return 0;
310
311 // The type table allows forward references. Push as many Opaque types as
312 // needed to get up to ID.
313 while (TypeList.size() <= ID)
314 TypeList.push_back(OpaqueType::get());
315 return TypeList.back().get();
316}
317
Chris Lattner48c85b82007-05-04 03:30:17 +0000318//===----------------------------------------------------------------------===//
319// Functions for parsing blocks from the bitcode file
320//===----------------------------------------------------------------------===//
321
Devang Patel05988662008-09-25 21:00:45 +0000322bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000323 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000324 return Error("Malformed block record");
325
Devang Patel19c87462008-09-26 22:53:05 +0000326 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000327 return Error("Multiple PARAMATTR blocks found!");
328
329 SmallVector<uint64_t, 64> Record;
330
Devang Patel05988662008-09-25 21:00:45 +0000331 SmallVector<AttributeWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000332
333 // Read all the records.
334 while (1) {
335 unsigned Code = Stream.ReadCode();
336 if (Code == bitc::END_BLOCK) {
337 if (Stream.ReadBlockEnd())
338 return Error("Error at end of PARAMATTR block");
339 return false;
340 }
341
342 if (Code == bitc::ENTER_SUBBLOCK) {
343 // No known subblocks, always skip them.
344 Stream.ReadSubBlockID();
345 if (Stream.SkipBlock())
346 return Error("Malformed block record");
347 continue;
348 }
349
350 if (Code == bitc::DEFINE_ABBREV) {
351 Stream.ReadAbbrevRecord();
352 continue;
353 }
354
355 // Read a record.
356 Record.clear();
357 switch (Stream.ReadRecord(Code, Record)) {
358 default: // Default behavior: ignore.
359 break;
360 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
361 if (Record.size() & 1)
362 return Error("Invalid ENTRY record");
363
Chris Lattner9a6cb152008-10-05 18:22:09 +0000364 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000365 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000366 // to index ~0. Index 0 is used for return value attributes but used to be
367 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000368 Attributes RetAttribute = Attribute::None;
369 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000370 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000371 // FIXME: remove in LLVM 3.0
372 // The alignment is stored as a 16-bit raw value from bits 31--16.
373 // We shift the bits above 31 down by 11 bits.
374
375 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
376 if (Alignment && !isPowerOf2_32(Alignment))
377 return Error("Alignment is not a power of two.");
378
379 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
380 if (Alignment)
381 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
382 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
383 Record[i+1] = ReconstitutedAttr;
384
Devang Patel19c87462008-09-26 22:53:05 +0000385 if (Record[i] == 0)
386 RetAttribute = Record[i+1];
387 else if (Record[i] == ~0U)
388 FnAttribute = Record[i+1];
389 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000390
391 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
392 Attribute::ReadOnly|Attribute::ReadNone);
393
394 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
395 (RetAttribute & OldRetAttrs) != 0) {
396 if (FnAttribute == Attribute::None) { // add a slot so they get added.
397 Record.push_back(~0U);
398 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000399 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000400
401 FnAttribute |= RetAttribute & OldRetAttrs;
402 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000403 }
Chris Lattner461edd92008-03-12 02:25:52 +0000404
Devang Patel19c87462008-09-26 22:53:05 +0000405 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000406 if (Record[i] == 0) {
407 if (RetAttribute != Attribute::None)
408 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
409 } else if (Record[i] == ~0U) {
410 if (FnAttribute != Attribute::None)
411 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
412 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000413 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
414 }
Devang Patel19c87462008-09-26 22:53:05 +0000415
416 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000417 Attrs.clear();
418 break;
419 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000420 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000421 }
422}
423
424
Chris Lattner86697142007-05-01 05:01:34 +0000425bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000426 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000427 return Error("Malformed block record");
428
429 if (!TypeList.empty())
430 return Error("Multiple TYPE_BLOCKs found!");
431
432 SmallVector<uint64_t, 64> Record;
433 unsigned NumRecords = 0;
434
435 // Read all the records for this type table.
436 while (1) {
437 unsigned Code = Stream.ReadCode();
438 if (Code == bitc::END_BLOCK) {
439 if (NumRecords != TypeList.size())
440 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000441 if (Stream.ReadBlockEnd())
442 return Error("Error at end of type table block");
443 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000444 }
445
446 if (Code == bitc::ENTER_SUBBLOCK) {
447 // No known subblocks, always skip them.
448 Stream.ReadSubBlockID();
449 if (Stream.SkipBlock())
450 return Error("Malformed block record");
451 continue;
452 }
453
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000454 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000455 Stream.ReadAbbrevRecord();
456 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000457 }
458
459 // Read a record.
460 Record.clear();
461 const Type *ResultTy = 0;
462 switch (Stream.ReadRecord(Code, Record)) {
463 default: // Default behavior: unknown type.
464 ResultTy = 0;
465 break;
466 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
467 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
468 // type list. This allows us to reserve space.
469 if (Record.size() < 1)
470 return Error("Invalid TYPE_CODE_NUMENTRY record");
471 TypeList.reserve(Record[0]);
472 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000473 case bitc::TYPE_CODE_VOID: // VOID
474 ResultTy = Type::VoidTy;
475 break;
476 case bitc::TYPE_CODE_FLOAT: // FLOAT
477 ResultTy = Type::FloatTy;
478 break;
479 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
480 ResultTy = Type::DoubleTy;
481 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000482 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
483 ResultTy = Type::X86_FP80Ty;
484 break;
485 case bitc::TYPE_CODE_FP128: // FP128
486 ResultTy = Type::FP128Ty;
487 break;
488 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
489 ResultTy = Type::PPC_FP128Ty;
490 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000491 case bitc::TYPE_CODE_LABEL: // LABEL
492 ResultTy = Type::LabelTy;
493 break;
494 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
495 ResultTy = 0;
496 break;
497 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
498 if (Record.size() < 1)
499 return Error("Invalid Integer type record");
500
501 ResultTy = IntegerType::get(Record[0]);
502 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000503 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
504 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000505 if (Record.size() < 1)
506 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000507 unsigned AddressSpace = 0;
508 if (Record.size() == 2)
509 AddressSpace = Record[1];
510 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000511 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000512 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000513 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000514 // FIXME: attrid is dead, remove it in LLVM 3.0
515 // FUNCTION: [vararg, attrid, retty, paramty x N]
516 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000517 return Error("Invalid FUNCTION type record");
518 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000519 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000520 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000521
Chris Lattnera1afde72007-11-27 17:48:06 +0000522 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000523 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000524 break;
525 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000526 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000527 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000528 return Error("Invalid STRUCT type record");
529 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000530 for (unsigned i = 1, e = Record.size(); i != e; ++i)
531 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000532 ResultTy = StructType::get(EltTys, Record[0]);
533 break;
534 }
535 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
536 if (Record.size() < 2)
537 return Error("Invalid ARRAY type record");
538 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
539 break;
540 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
541 if (Record.size() < 2)
542 return Error("Invalid VECTOR type record");
543 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
544 break;
545 }
546
547 if (NumRecords == TypeList.size()) {
548 // If this is a new type slot, just append it.
549 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
550 ++NumRecords;
551 } else if (ResultTy == 0) {
552 // Otherwise, this was forward referenced, so an opaque type was created,
553 // but the result type is actually just an opaque. Leave the one we
554 // created previously.
555 ++NumRecords;
556 } else {
557 // Otherwise, this was forward referenced, so an opaque type was created.
558 // Resolve the opaque type to the real type now.
559 assert(NumRecords < TypeList.size() && "Typelist imbalance");
560 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
561
562 // Don't directly push the new type on the Tab. Instead we want to replace
563 // the opaque type we previously inserted with the new concrete value. The
564 // refinement from the abstract (opaque) type to the new type causes all
565 // uses of the abstract type to use the concrete type (NewTy). This will
566 // also cause the opaque type to be deleted.
567 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
568
569 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000570 // value table... or with a preexisting type that was already in the
571 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 assert(TypeList[NumRecords-1].get() != OldTy &&
573 "refineAbstractType didn't work!");
574 }
575 }
576}
577
578
Chris Lattner86697142007-05-01 05:01:34 +0000579bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000580 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000581 return Error("Malformed block record");
582
583 SmallVector<uint64_t, 64> Record;
584
585 // Read all the records for this type table.
586 std::string TypeName;
587 while (1) {
588 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000589 if (Code == bitc::END_BLOCK) {
590 if (Stream.ReadBlockEnd())
591 return Error("Error at end of type symbol table block");
592 return false;
593 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000594
595 if (Code == bitc::ENTER_SUBBLOCK) {
596 // No known subblocks, always skip them.
597 Stream.ReadSubBlockID();
598 if (Stream.SkipBlock())
599 return Error("Malformed block record");
600 continue;
601 }
602
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000603 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000604 Stream.ReadAbbrevRecord();
605 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000606 }
607
608 // Read a record.
609 Record.clear();
610 switch (Stream.ReadRecord(Code, Record)) {
611 default: // Default behavior: unknown type.
612 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000613 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000614 if (ConvertToString(Record, 1, TypeName))
615 return Error("Invalid TST_ENTRY record");
616 unsigned TypeID = Record[0];
617 if (TypeID >= TypeList.size())
618 return Error("Invalid Type ID in TST_ENTRY record");
619
620 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
621 TypeName.clear();
622 break;
623 }
624 }
625}
626
Chris Lattner86697142007-05-01 05:01:34 +0000627bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000628 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000629 return Error("Malformed block record");
630
631 SmallVector<uint64_t, 64> Record;
632
633 // Read all the records for this value table.
634 SmallString<128> ValueName;
635 while (1) {
636 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000637 if (Code == bitc::END_BLOCK) {
638 if (Stream.ReadBlockEnd())
639 return Error("Error at end of value symbol table block");
640 return false;
641 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000642 if (Code == bitc::ENTER_SUBBLOCK) {
643 // No known subblocks, always skip them.
644 Stream.ReadSubBlockID();
645 if (Stream.SkipBlock())
646 return Error("Malformed block record");
647 continue;
648 }
649
650 if (Code == bitc::DEFINE_ABBREV) {
651 Stream.ReadAbbrevRecord();
652 continue;
653 }
654
655 // Read a record.
656 Record.clear();
657 switch (Stream.ReadRecord(Code, Record)) {
658 default: // Default behavior: unknown type.
659 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000660 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000661 if (ConvertToString(Record, 1, ValueName))
662 return Error("Invalid TST_ENTRY record");
663 unsigned ValueID = Record[0];
664 if (ValueID >= ValueList.size())
665 return Error("Invalid Value ID in VST_ENTRY record");
666 Value *V = ValueList[ValueID];
667
668 V->setName(&ValueName[0], ValueName.size());
669 ValueName.clear();
670 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000671 }
672 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000673 if (ConvertToString(Record, 1, ValueName))
674 return Error("Invalid VST_BBENTRY record");
675 BasicBlock *BB = getBasicBlock(Record[0]);
676 if (BB == 0)
677 return Error("Invalid BB ID in VST_BBENTRY record");
678
679 BB->setName(&ValueName[0], ValueName.size());
680 ValueName.clear();
681 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000682 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000683 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000684 }
685}
686
Chris Lattner0eef0802007-04-24 04:04:35 +0000687/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
688/// the LSB for dense VBR encoding.
689static uint64_t DecodeSignRotatedValue(uint64_t V) {
690 if ((V & 1) == 0)
691 return V >> 1;
692 if (V != 1)
693 return -(V >> 1);
694 // There is no such thing as -0 with integers. "-0" really means MININT.
695 return 1ULL << 63;
696}
697
Chris Lattner07d98b42007-04-26 02:46:40 +0000698/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
699/// values and aliases that we can.
700bool BitcodeReader::ResolveGlobalAndAliasInits() {
701 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
702 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
703
704 GlobalInitWorklist.swap(GlobalInits);
705 AliasInitWorklist.swap(AliasInits);
706
707 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000708 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000709 if (ValID >= ValueList.size()) {
710 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000711 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000712 } else {
713 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
714 GlobalInitWorklist.back().first->setInitializer(C);
715 else
716 return Error("Global variable initializer is not a constant!");
717 }
718 GlobalInitWorklist.pop_back();
719 }
720
721 while (!AliasInitWorklist.empty()) {
722 unsigned ValID = AliasInitWorklist.back().second;
723 if (ValID >= ValueList.size()) {
724 AliasInits.push_back(AliasInitWorklist.back());
725 } else {
726 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000727 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000728 else
729 return Error("Alias initializer is not a constant!");
730 }
731 AliasInitWorklist.pop_back();
732 }
733 return false;
734}
735
736
Chris Lattner86697142007-05-01 05:01:34 +0000737bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000738 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000739 return Error("Malformed block record");
740
741 SmallVector<uint64_t, 64> Record;
742
743 // Read all the records for this value table.
744 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000745 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000746 while (1) {
747 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000748 if (Code == bitc::END_BLOCK)
749 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000750
751 if (Code == bitc::ENTER_SUBBLOCK) {
752 // No known subblocks, always skip them.
753 Stream.ReadSubBlockID();
754 if (Stream.SkipBlock())
755 return Error("Malformed block record");
756 continue;
757 }
758
759 if (Code == bitc::DEFINE_ABBREV) {
760 Stream.ReadAbbrevRecord();
761 continue;
762 }
763
764 // Read a record.
765 Record.clear();
766 Value *V = 0;
767 switch (Stream.ReadRecord(Code, Record)) {
768 default: // Default behavior: unknown constant
769 case bitc::CST_CODE_UNDEF: // UNDEF
770 V = UndefValue::get(CurTy);
771 break;
772 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
773 if (Record.empty())
774 return Error("Malformed CST_SETTYPE record");
775 if (Record[0] >= TypeList.size())
776 return Error("Invalid Type ID in CST_SETTYPE record");
777 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000778 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000779 case bitc::CST_CODE_NULL: // NULL
780 V = Constant::getNullValue(CurTy);
781 break;
782 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000783 if (!isa<IntegerType>(CurTy) || Record.empty())
784 return Error("Invalid CST_INTEGER record");
785 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
786 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000787 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
788 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000789 return Error("Invalid WIDE_INTEGER record");
790
Chris Lattner15e6d172007-05-04 19:11:41 +0000791 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000792 SmallVector<uint64_t, 8> Words;
793 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000794 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000795 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000796 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000797 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000798 break;
799 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000800 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000801 if (Record.empty())
802 return Error("Invalid FLOAT record");
803 if (CurTy == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000804 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000805 else if (CurTy == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000806 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000807 else if (CurTy == Type::X86_FP80Ty) {
808 // Bits are not stored the same way as a normal i80 APInt, compensate.
809 uint64_t Rearrange[2];
810 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
811 Rearrange[1] = Record[0] >> 48;
812 V = ConstantFP::get(APFloat(APInt(80, 2, Rearrange)));
813 } else if (CurTy == Type::FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000814 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000815 else if (CurTy == Type::PPC_FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000816 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000817 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000818 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000819 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000820 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000821
Chris Lattner15e6d172007-05-04 19:11:41 +0000822 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
823 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000824 return Error("Invalid CST_AGGREGATE record");
825
Chris Lattner15e6d172007-05-04 19:11:41 +0000826 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000827 std::vector<Constant*> Elts;
828
829 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
830 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000831 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000832 STy->getElementType(i)));
833 V = ConstantStruct::get(STy, Elts);
834 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
835 const Type *EltTy = ATy->getElementType();
836 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000837 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000838 V = ConstantArray::get(ATy, Elts);
839 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
840 const Type *EltTy = VTy->getElementType();
841 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000842 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000843 V = ConstantVector::get(Elts);
844 } else {
845 V = UndefValue::get(CurTy);
846 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000847 break;
848 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000849 case bitc::CST_CODE_STRING: { // STRING: [values]
850 if (Record.empty())
851 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000852
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000853 const ArrayType *ATy = cast<ArrayType>(CurTy);
854 const Type *EltTy = ATy->getElementType();
855
856 unsigned Size = Record.size();
857 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000858 for (unsigned i = 0; i != Size; ++i)
859 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
860 V = ConstantArray::get(ATy, Elts);
861 break;
862 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000863 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
864 if (Record.empty())
865 return Error("Invalid CST_AGGREGATE record");
866
867 const ArrayType *ATy = cast<ArrayType>(CurTy);
868 const Type *EltTy = ATy->getElementType();
869
870 unsigned Size = Record.size();
871 std::vector<Constant*> Elts;
872 for (unsigned i = 0; i != Size; ++i)
873 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
874 Elts.push_back(Constant::getNullValue(EltTy));
875 V = ConstantArray::get(ATy, Elts);
876 break;
877 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000878 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
879 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
880 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000881 if (Opc < 0) {
882 V = UndefValue::get(CurTy); // Unknown binop.
883 } else {
884 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
885 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
886 V = ConstantExpr::get(Opc, LHS, RHS);
887 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000888 break;
889 }
890 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
891 if (Record.size() < 3) return Error("Invalid CE_CAST record");
892 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000893 if (Opc < 0) {
894 V = UndefValue::get(CurTy); // Unknown cast.
895 } else {
896 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000897 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000898 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
899 V = ConstantExpr::getCast(Opc, Op, CurTy);
900 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000901 break;
902 }
903 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000904 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000905 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000906 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000907 const Type *ElTy = getTypeByID(Record[i]);
908 if (!ElTy) return Error("Invalid CE_GEP record");
909 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
910 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000911 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
912 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000913 }
914 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
915 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
916 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
917 Type::Int1Ty),
918 ValueList.getConstantFwdRef(Record[1],CurTy),
919 ValueList.getConstantFwdRef(Record[2],CurTy));
920 break;
921 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
922 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
923 const VectorType *OpTy =
924 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
925 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
926 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerba120aa2009-02-03 02:11:28 +0000927 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000928 V = ConstantExpr::getExtractElement(Op0, Op1);
929 break;
930 }
931 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
932 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
933 if (Record.size() < 3 || OpTy == 0)
934 return Error("Invalid CE_INSERTELT record");
935 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
936 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
937 OpTy->getElementType());
938 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
939 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
940 break;
941 }
942 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
943 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
944 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +0000945 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000946 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
947 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
948 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
949 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
950 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
951 break;
952 }
Nate Begeman0f123cf2009-02-12 21:28:33 +0000953 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
954 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
955 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
956 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
957 return Error("Invalid CE_SHUFVEC_EX record");
958 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
959 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
960 const Type *ShufTy=VectorType::get(Type::Int32Ty, RTy->getNumElements());
961 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
962 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
963 break;
964 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000965 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
966 if (Record.size() < 4) return Error("Invalid CE_CMP record");
967 const Type *OpTy = getTypeByID(Record[0]);
968 if (OpTy == 0) return Error("Invalid CE_CMP record");
969 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
970 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
971
972 if (OpTy->isFloatingPoint())
973 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanbaa64eb2008-05-12 20:33:52 +0000974 else if (!isa<VectorType>(OpTy))
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000975 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +0000976 else if (OpTy->isFPOrFPVector())
977 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
978 else
979 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000980 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000981 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000982 case bitc::CST_CODE_INLINEASM: {
983 if (Record.size() < 2) return Error("Invalid INLINEASM record");
984 std::string AsmStr, ConstrStr;
985 bool HasSideEffects = Record[0];
986 unsigned AsmStrSize = Record[1];
987 if (2+AsmStrSize >= Record.size())
988 return Error("Invalid INLINEASM record");
989 unsigned ConstStrSize = Record[2+AsmStrSize];
990 if (3+AsmStrSize+ConstStrSize > Record.size())
991 return Error("Invalid INLINEASM record");
992
993 for (unsigned i = 0; i != AsmStrSize; ++i)
994 AsmStr += (char)Record[2+i];
995 for (unsigned i = 0; i != ConstStrSize; ++i)
996 ConstrStr += (char)Record[3+AsmStrSize+i];
997 const PointerType *PTy = cast<PointerType>(CurTy);
998 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
999 AsmStr, ConstrStr, HasSideEffects);
1000 break;
1001 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001002 }
1003
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001004 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001005 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001006 }
Chris Lattnerea693df2008-08-21 02:34:16 +00001007
1008 if (NextCstNo != ValueList.size())
1009 return Error("Invalid constant reference!");
1010
1011 if (Stream.ReadBlockEnd())
1012 return Error("Error at end of constants block");
1013
1014 // Once all the constants have been read, go through and resolve forward
1015 // references.
1016 ValueList.ResolveConstantForwardRefs();
1017 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001018}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001019
Chris Lattner980e5aa2007-05-01 05:52:21 +00001020/// RememberAndSkipFunctionBody - When we see the block for a function body,
1021/// remember where it is and then skip it. This lets us lazily deserialize the
1022/// functions.
1023bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001024 // Get the function we are talking about.
1025 if (FunctionsWithBodies.empty())
1026 return Error("Insufficient function protos");
1027
1028 Function *Fn = FunctionsWithBodies.back();
1029 FunctionsWithBodies.pop_back();
1030
1031 // Save the current stream state.
1032 uint64_t CurBit = Stream.GetCurrentBitNo();
1033 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1034
1035 // Set the functions linkage to GhostLinkage so we know it is lazily
1036 // deserialized.
1037 Fn->setLinkage(GlobalValue::GhostLinkage);
1038
1039 // Skip over the function block for now.
1040 if (Stream.SkipBlock())
1041 return Error("Malformed block record");
1042 return false;
1043}
1044
Chris Lattner86697142007-05-01 05:01:34 +00001045bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001046 // Reject multiple MODULE_BLOCK's in a single bitstream.
1047 if (TheModule)
1048 return Error("Multiple MODULE_BLOCKs in same stream");
1049
Chris Lattnere17b6582007-05-05 00:17:00 +00001050 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001051 return Error("Malformed block record");
1052
1053 // Otherwise, create the module.
1054 TheModule = new Module(ModuleID);
1055
1056 SmallVector<uint64_t, 64> Record;
1057 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001058 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001059
1060 // Read all the records for this module.
1061 while (!Stream.AtEndOfStream()) {
1062 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001063 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001064 if (Stream.ReadBlockEnd())
1065 return Error("Error at end of module block");
1066
1067 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001068 ResolveGlobalAndAliasInits();
1069 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001070 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001071 if (!FunctionsWithBodies.empty())
1072 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001073
Chandler Carruth69940402007-08-04 01:51:18 +00001074 // Look for intrinsic functions which need to be upgraded at some point
1075 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1076 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001077 Function* NewFn;
1078 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001079 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1080 }
1081
Chris Lattner980e5aa2007-05-01 05:52:21 +00001082 // Force deallocation of memory for these vectors to favor the client that
1083 // want lazy deserialization.
1084 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1085 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1086 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001087 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001088 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001089
1090 if (Code == bitc::ENTER_SUBBLOCK) {
1091 switch (Stream.ReadSubBlockID()) {
1092 default: // Skip unknown content.
1093 if (Stream.SkipBlock())
1094 return Error("Malformed block record");
1095 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001096 case bitc::BLOCKINFO_BLOCK_ID:
1097 if (Stream.ReadBlockInfoBlock())
1098 return Error("Malformed BlockInfoBlock");
1099 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001100 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001101 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001102 return true;
1103 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001104 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001105 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001106 return true;
1107 break;
1108 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001109 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001110 return true;
1111 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001112 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001113 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001114 return true;
1115 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001116 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001117 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001118 return true;
1119 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001120 case bitc::FUNCTION_BLOCK_ID:
1121 // If this is the first function body we've seen, reverse the
1122 // FunctionsWithBodies list.
1123 if (!HasReversedFunctionsWithBodies) {
1124 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1125 HasReversedFunctionsWithBodies = true;
1126 }
1127
Chris Lattner980e5aa2007-05-01 05:52:21 +00001128 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001129 return true;
1130 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001131 }
1132 continue;
1133 }
1134
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001135 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001136 Stream.ReadAbbrevRecord();
1137 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001138 }
1139
1140 // Read a record.
1141 switch (Stream.ReadRecord(Code, Record)) {
1142 default: break; // Default behavior, ignore unknown content.
1143 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1144 if (Record.size() < 1)
1145 return Error("Malformed MODULE_CODE_VERSION");
1146 // Only version #0 is supported so far.
1147 if (Record[0] != 0)
1148 return Error("Unknown bitstream version!");
1149 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001150 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001151 std::string S;
1152 if (ConvertToString(Record, 0, S))
1153 return Error("Invalid MODULE_CODE_TRIPLE record");
1154 TheModule->setTargetTriple(S);
1155 break;
1156 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001157 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001158 std::string S;
1159 if (ConvertToString(Record, 0, S))
1160 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1161 TheModule->setDataLayout(S);
1162 break;
1163 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001164 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001165 std::string S;
1166 if (ConvertToString(Record, 0, S))
1167 return Error("Invalid MODULE_CODE_ASM record");
1168 TheModule->setModuleInlineAsm(S);
1169 break;
1170 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001171 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001172 std::string S;
1173 if (ConvertToString(Record, 0, S))
1174 return Error("Invalid MODULE_CODE_DEPLIB record");
1175 TheModule->addLibrary(S);
1176 break;
1177 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001178 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001179 std::string S;
1180 if (ConvertToString(Record, 0, S))
1181 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1182 SectionTable.push_back(S);
1183 break;
1184 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001185 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001186 std::string S;
1187 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001188 return Error("Invalid MODULE_CODE_GCNAME record");
1189 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001190 break;
1191 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001192 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001193 // linkage, alignment, section, visibility, threadlocal]
1194 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001195 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001196 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1197 const Type *Ty = getTypeByID(Record[0]);
1198 if (!isa<PointerType>(Ty))
1199 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001200 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001201 Ty = cast<PointerType>(Ty)->getElementType();
1202
1203 bool isConstant = Record[1];
1204 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1205 unsigned Alignment = (1 << Record[4]) >> 1;
1206 std::string Section;
1207 if (Record[5]) {
1208 if (Record[5]-1 >= SectionTable.size())
1209 return Error("Invalid section ID");
1210 Section = SectionTable[Record[5]-1];
1211 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001212 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001213 if (Record.size() > 6)
1214 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001215 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001216 if (Record.size() > 7)
1217 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001218
1219 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001220 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1221 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001222 NewGV->setAlignment(Alignment);
1223 if (!Section.empty())
1224 NewGV->setSection(Section);
1225 NewGV->setVisibility(Visibility);
1226 NewGV->setThreadLocal(isThreadLocal);
1227
Chris Lattner0b2482a2007-04-23 21:26:05 +00001228 ValueList.push_back(NewGV);
1229
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001230 // Remember which value to use for the global initializer.
1231 if (unsigned InitID = Record[2])
1232 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001233 break;
1234 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001235 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001236 // alignment, section, visibility, gc]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001237 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001238 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001239 return Error("Invalid MODULE_CODE_FUNCTION record");
1240 const Type *Ty = getTypeByID(Record[0]);
1241 if (!isa<PointerType>(Ty))
1242 return Error("Function not a pointer type!");
1243 const FunctionType *FTy =
1244 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1245 if (!FTy)
1246 return Error("Function not a pointer to function type!");
1247
Gabor Greif051a9502008-04-06 20:25:17 +00001248 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1249 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001250
1251 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001252 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001253 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001254 Func->setAttributes(getAttributes(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001255
1256 Func->setAlignment((1 << Record[5]) >> 1);
1257 if (Record[6]) {
1258 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001259 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001260 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001261 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001262 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001263 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001264 if (Record[8]-1 > GCTable.size())
1265 return Error("Invalid GC ID");
1266 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001267 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001268 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001269
1270 // If this is a function with a body, remember the prototype we are
1271 // creating now, so that we can match up the body with them later.
1272 if (!isProto)
1273 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001274 break;
1275 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001276 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001277 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001278 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001279 if (Record.size() < 3)
1280 return Error("Invalid MODULE_ALIAS record");
1281 const Type *Ty = getTypeByID(Record[0]);
1282 if (!isa<PointerType>(Ty))
1283 return Error("Function not a pointer type!");
1284
1285 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1286 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001287 // Old bitcode files didn't have visibility field.
1288 if (Record.size() > 3)
1289 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001290 ValueList.push_back(NewGA);
1291 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1292 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001293 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001294 /// MODULE_CODE_PURGEVALS: [numvals]
1295 case bitc::MODULE_CODE_PURGEVALS:
1296 // Trim down the value list to the specified size.
1297 if (Record.size() < 1 || Record[0] > ValueList.size())
1298 return Error("Invalid MODULE_PURGEVALS record");
1299 ValueList.shrinkTo(Record[0]);
1300 break;
1301 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001302 Record.clear();
1303 }
1304
1305 return Error("Premature end of bitstream");
1306}
1307
Chris Lattner6fa6a322008-07-09 05:14:23 +00001308/// SkipWrapperHeader - Some systems wrap bc files with a special header for
1309/// padding or other reasons. The format of this header is:
1310///
1311/// struct bc_header {
1312/// uint32_t Magic; // 0x0B17C0DE
1313/// uint32_t Version; // Version, currently always 0.
1314/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1315/// uint32_t BitcodeSize; // Size of traditional bitcode file.
1316/// ... potentially other gunk ...
1317/// };
1318///
1319/// This function is called when we find a file with a matching magic number.
1320/// In this case, skip down to the subsection of the file that is actually a BC
1321/// file.
1322static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1323 enum {
1324 KnownHeaderSize = 4*4, // Size of header we read.
1325 OffsetField = 2*4, // Offset in bytes to Offset field.
1326 SizeField = 3*4 // Offset in bytes to Size field.
1327 };
1328
1329
1330 // Must contain the header!
1331 if (BufEnd-BufPtr < KnownHeaderSize) return true;
1332
1333 unsigned Offset = ( BufPtr[OffsetField ] |
1334 (BufPtr[OffsetField+1] << 8) |
1335 (BufPtr[OffsetField+2] << 16) |
1336 (BufPtr[OffsetField+3] << 24));
1337 unsigned Size = ( BufPtr[SizeField ] |
1338 (BufPtr[SizeField +1] << 8) |
1339 (BufPtr[SizeField +2] << 16) |
1340 (BufPtr[SizeField +3] << 24));
1341
1342 // Verify that Offset+Size fits in the file.
1343 if (Offset+Size > unsigned(BufEnd-BufPtr))
1344 return true;
1345 BufPtr += Offset;
1346 BufEnd = BufPtr+Size;
1347 return false;
1348}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001349
Chris Lattnerc453f762007-04-29 07:54:31 +00001350bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001351 TheModule = 0;
1352
Chris Lattnerc453f762007-04-29 07:54:31 +00001353 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001354 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1355
Chris Lattnerc453f762007-04-29 07:54:31 +00001356 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001357 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1358
1359 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1360 // The magic number is 0x0B17C0DE stored in little endian.
1361 if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1362 BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1363 if (SkipWrapperHeader(BufPtr, BufEnd))
1364 return Error("Invalid bitcode wrapper header");
1365
1366 Stream.init(BufPtr, BufEnd);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001367
1368 // Sniff for the signature.
1369 if (Stream.Read(8) != 'B' ||
1370 Stream.Read(8) != 'C' ||
1371 Stream.Read(4) != 0x0 ||
1372 Stream.Read(4) != 0xC ||
1373 Stream.Read(4) != 0xE ||
1374 Stream.Read(4) != 0xD)
1375 return Error("Invalid bitcode signature");
1376
1377 // We expect a number of well-defined blocks, though we don't necessarily
1378 // need to understand them all.
1379 while (!Stream.AtEndOfStream()) {
1380 unsigned Code = Stream.ReadCode();
1381
1382 if (Code != bitc::ENTER_SUBBLOCK)
1383 return Error("Invalid record at top-level");
1384
1385 unsigned BlockID = Stream.ReadSubBlockID();
1386
1387 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001388 switch (BlockID) {
1389 case bitc::BLOCKINFO_BLOCK_ID:
1390 if (Stream.ReadBlockInfoBlock())
1391 return Error("Malformed BlockInfoBlock");
1392 break;
1393 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001394 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001395 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001396 break;
1397 default:
1398 if (Stream.SkipBlock())
1399 return Error("Malformed block record");
1400 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001401 }
1402 }
1403
1404 return false;
1405}
Chris Lattnerc453f762007-04-29 07:54:31 +00001406
Chris Lattner48f84872007-05-01 04:59:48 +00001407
Chris Lattner980e5aa2007-05-01 05:52:21 +00001408/// ParseFunctionBody - Lazily parse the specified function body block.
1409bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001410 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001411 return Error("Malformed block record");
1412
1413 unsigned ModuleValueListSize = ValueList.size();
1414
1415 // Add all the function arguments to the value table.
1416 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1417 ValueList.push_back(I);
1418
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001419 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001420 BasicBlock *CurBB = 0;
1421 unsigned CurBBNo = 0;
1422
Chris Lattner980e5aa2007-05-01 05:52:21 +00001423 // Read all the records.
1424 SmallVector<uint64_t, 64> Record;
1425 while (1) {
1426 unsigned Code = Stream.ReadCode();
1427 if (Code == bitc::END_BLOCK) {
1428 if (Stream.ReadBlockEnd())
1429 return Error("Error at end of function block");
1430 break;
1431 }
1432
1433 if (Code == bitc::ENTER_SUBBLOCK) {
1434 switch (Stream.ReadSubBlockID()) {
1435 default: // Skip unknown content.
1436 if (Stream.SkipBlock())
1437 return Error("Malformed block record");
1438 break;
1439 case bitc::CONSTANTS_BLOCK_ID:
1440 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001441 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001442 break;
1443 case bitc::VALUE_SYMTAB_BLOCK_ID:
1444 if (ParseValueSymbolTable()) return true;
1445 break;
1446 }
1447 continue;
1448 }
1449
1450 if (Code == bitc::DEFINE_ABBREV) {
1451 Stream.ReadAbbrevRecord();
1452 continue;
1453 }
1454
1455 // Read a record.
1456 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001457 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001458 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001459 default: // Default behavior: reject
1460 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001461 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001462 if (Record.size() < 1 || Record[0] == 0)
1463 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001464 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001465 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001466 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001467 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001468 CurBB = FunctionBBs[0];
1469 continue;
1470
Chris Lattnerabfbf852007-05-06 00:21:25 +00001471 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1472 unsigned OpNum = 0;
1473 Value *LHS, *RHS;
1474 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1475 getValue(Record, OpNum, LHS->getType(), RHS) ||
1476 OpNum+1 != Record.size())
1477 return Error("Invalid BINOP record");
1478
1479 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1480 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001481 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001482 break;
1483 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001484 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1485 unsigned OpNum = 0;
1486 Value *Op;
1487 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1488 OpNum+2 != Record.size())
1489 return Error("Invalid CAST record");
1490
1491 const Type *ResTy = getTypeByID(Record[OpNum]);
1492 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1493 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001494 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001495 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001496 break;
1497 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001498 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001499 unsigned OpNum = 0;
1500 Value *BasePtr;
1501 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001502 return Error("Invalid GEP record");
1503
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001504 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001505 while (OpNum != Record.size()) {
1506 Value *Op;
1507 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001508 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001509 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001510 }
1511
Gabor Greif051a9502008-04-06 20:25:17 +00001512 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001513 break;
1514 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001515
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001516 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1517 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001518 unsigned OpNum = 0;
1519 Value *Agg;
1520 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1521 return Error("Invalid EXTRACTVAL record");
1522
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001523 SmallVector<unsigned, 4> EXTRACTVALIdx;
1524 for (unsigned RecSize = Record.size();
1525 OpNum != RecSize; ++OpNum) {
1526 uint64_t Index = Record[OpNum];
1527 if ((unsigned)Index != Index)
1528 return Error("Invalid EXTRACTVAL index");
1529 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001530 }
1531
1532 I = ExtractValueInst::Create(Agg,
1533 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1534 break;
1535 }
1536
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001537 case bitc::FUNC_CODE_INST_INSERTVAL: {
1538 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001539 unsigned OpNum = 0;
1540 Value *Agg;
1541 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1542 return Error("Invalid INSERTVAL record");
1543 Value *Val;
1544 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1545 return Error("Invalid INSERTVAL record");
1546
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001547 SmallVector<unsigned, 4> INSERTVALIdx;
1548 for (unsigned RecSize = Record.size();
1549 OpNum != RecSize; ++OpNum) {
1550 uint64_t Index = Record[OpNum];
1551 if ((unsigned)Index != Index)
1552 return Error("Invalid INSERTVAL index");
1553 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001554 }
1555
1556 I = InsertValueInst::Create(Agg, Val,
1557 INSERTVALIdx.begin(), INSERTVALIdx.end());
1558 break;
1559 }
1560
Chris Lattnerabfbf852007-05-06 00:21:25 +00001561 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001562 // obsolete form of select
1563 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00001564 unsigned OpNum = 0;
1565 Value *TrueVal, *FalseVal, *Cond;
1566 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1567 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Dan Gohmanbe919402008-09-09 02:08:49 +00001568 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001569 return Error("Invalid SELECT record");
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001570
1571 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1572 break;
1573 }
1574
1575 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1576 // new form of select
1577 // handles select i1 or select [N x i1]
1578 unsigned OpNum = 0;
1579 Value *TrueVal, *FalseVal, *Cond;
1580 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1581 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1582 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1583 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001584
1585 // select condition can be either i1 or [N x i1]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001586 if (const VectorType* vector_type =
1587 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00001588 // expect <n x i1>
1589 if (vector_type->getElementType() != Type::Int1Ty)
1590 return Error("Invalid SELECT condition type");
1591 } else {
1592 // expect i1
1593 if (Cond->getType() != Type::Int1Ty)
1594 return Error("Invalid SELECT condition type");
1595 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001596
Gabor Greif051a9502008-04-06 20:25:17 +00001597 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001598 break;
1599 }
1600
1601 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001602 unsigned OpNum = 0;
1603 Value *Vec, *Idx;
1604 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1605 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001606 return Error("Invalid EXTRACTELT record");
1607 I = new ExtractElementInst(Vec, Idx);
1608 break;
1609 }
1610
1611 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001612 unsigned OpNum = 0;
1613 Value *Vec, *Elt, *Idx;
1614 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1615 getValue(Record, OpNum,
1616 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1617 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001618 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001619 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001620 break;
1621 }
1622
Chris Lattnerabfbf852007-05-06 00:21:25 +00001623 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1624 unsigned OpNum = 0;
1625 Value *Vec1, *Vec2, *Mask;
1626 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1627 getValue(Record, OpNum, Vec1->getType(), Vec2))
1628 return Error("Invalid SHUFFLEVEC record");
1629
Mon P Wangaeb06d22008-11-10 04:46:22 +00001630 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001631 return Error("Invalid SHUFFLEVEC record");
1632 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1633 break;
1634 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001635
Chris Lattner01ff65f2007-05-02 05:16:49 +00001636 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001637 // VFCmp/VICmp
1638 // or old form of ICmp/FCmp returning bool
Chris Lattner7337ab92007-05-06 00:00:00 +00001639 unsigned OpNum = 0;
1640 Value *LHS, *RHS;
1641 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1642 getValue(Record, OpNum, LHS->getType(), RHS) ||
1643 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001644 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001645
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001646 if (LHS->getType()->isFloatingPoint())
Nate Begemanac80ade2008-05-12 19:01:56 +00001647 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001648 else if (!isa<VectorType>(LHS->getType()))
1649 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanac80ade2008-05-12 19:01:56 +00001650 else if (LHS->getType()->isFPOrFPVector())
1651 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1652 else
1653 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001654 break;
1655 }
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001656 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1657 // Fcmp/ICmp returning bool or vector of bool
Dan Gohmanf72fb672008-09-09 01:02:47 +00001658 unsigned OpNum = 0;
1659 Value *LHS, *RHS;
1660 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1661 getValue(Record, OpNum, LHS->getType(), RHS) ||
1662 OpNum+1 != Record.size())
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001663 return Error("Invalid CMP2 record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001664
Dan Gohmanf72fb672008-09-09 01:02:47 +00001665 if (LHS->getType()->isFPOrFPVector())
1666 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1667 else
1668 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1669 break;
1670 }
Devang Patel197be3d2008-02-22 02:49:49 +00001671 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1672 if (Record.size() != 2)
1673 return Error("Invalid GETRESULT record");
1674 unsigned OpNum = 0;
1675 Value *Op;
1676 getValueTypePair(Record, OpNum, NextValueNo, Op);
1677 unsigned Index = Record[1];
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001678 I = ExtractValueInst::Create(Op, Index);
Devang Patel197be3d2008-02-22 02:49:49 +00001679 break;
1680 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001681
Chris Lattner231cbcb2007-05-02 04:27:25 +00001682 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001683 {
1684 unsigned Size = Record.size();
1685 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001686 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001687 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001688 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00001689
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001690 unsigned OpNum = 0;
1691 SmallVector<Value *,4> Vs;
1692 do {
1693 Value *Op = NULL;
1694 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1695 return Error("Invalid RET record");
1696 Vs.push_back(Op);
1697 } while(OpNum != Record.size());
1698
1699 const Type *ReturnType = F->getReturnType();
1700 if (Vs.size() > 1 ||
1701 (isa<StructType>(ReturnType) &&
1702 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1703 Value *RV = UndefValue::get(ReturnType);
1704 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1705 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1706 CurBB->getInstList().push_back(I);
1707 ValueList.AssignValue(I, NextValueNo++);
1708 RV = I;
1709 }
1710 I = ReturnInst::Create(RV);
Devang Pateld9d99ff2008-02-26 01:29:32 +00001711 break;
1712 }
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001713
1714 I = ReturnInst::Create(Vs[0]);
1715 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00001716 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001717 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001718 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001719 return Error("Invalid BR record");
1720 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1721 if (TrueDest == 0)
1722 return Error("Invalid BR record");
1723
1724 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001725 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001726 else {
1727 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1728 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1729 if (FalseDest == 0 || Cond == 0)
1730 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001731 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001732 }
1733 break;
1734 }
1735 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1736 if (Record.size() < 3 || (Record.size() & 1) == 0)
1737 return Error("Invalid SWITCH record");
1738 const Type *OpTy = getTypeByID(Record[0]);
1739 Value *Cond = getFnValueByID(Record[1], OpTy);
1740 BasicBlock *Default = getBasicBlock(Record[2]);
1741 if (OpTy == 0 || Cond == 0 || Default == 0)
1742 return Error("Invalid SWITCH record");
1743 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001744 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001745 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1746 ConstantInt *CaseVal =
1747 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1748 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1749 if (CaseVal == 0 || DestBB == 0) {
1750 delete SI;
1751 return Error("Invalid SWITCH record!");
1752 }
1753 SI->addCase(CaseVal, DestBB);
1754 }
1755 I = SI;
1756 break;
1757 }
1758
Duncan Sandsdc024672007-11-27 13:23:08 +00001759 case bitc::FUNC_CODE_INST_INVOKE: {
1760 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001761 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00001762 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001763 unsigned CCInfo = Record[1];
1764 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1765 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001766
Chris Lattnera9bb7132007-05-08 05:38:01 +00001767 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001768 Value *Callee;
1769 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001770 return Error("Invalid INVOKE record");
1771
Chris Lattner7337ab92007-05-06 00:00:00 +00001772 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1773 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001774 dyn_cast<FunctionType>(CalleeTy->getElementType());
1775
1776 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001777 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1778 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001779 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001780
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001781 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001782 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1783 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1784 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001785 }
1786
Chris Lattner7337ab92007-05-06 00:00:00 +00001787 if (!FTy->isVarArg()) {
1788 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001789 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001790 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001791 // Read type/value pairs for varargs params.
1792 while (OpNum != Record.size()) {
1793 Value *Op;
1794 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1795 return Error("Invalid INVOKE record");
1796 Ops.push_back(Op);
1797 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001798 }
1799
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001800 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1801 Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001802 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Devang Patel05988662008-09-25 21:00:45 +00001803 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001804 break;
1805 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001806 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1807 I = new UnwindInst();
1808 break;
1809 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1810 I = new UnreachableInst();
1811 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001812 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001813 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001814 return Error("Invalid PHI record");
1815 const Type *Ty = getTypeByID(Record[0]);
1816 if (!Ty) return Error("Invalid PHI record");
1817
Gabor Greif051a9502008-04-06 20:25:17 +00001818 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001819 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001820
Chris Lattner15e6d172007-05-04 19:11:41 +00001821 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1822 Value *V = getFnValueByID(Record[1+i], Ty);
1823 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001824 if (!V || !BB) return Error("Invalid PHI record");
1825 PN->addIncoming(V, BB);
1826 }
1827 I = PN;
1828 break;
1829 }
1830
1831 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1832 if (Record.size() < 3)
1833 return Error("Invalid MALLOC record");
1834 const PointerType *Ty =
1835 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1836 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1837 unsigned Align = Record[2];
1838 if (!Ty || !Size) return Error("Invalid MALLOC record");
1839 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1840 break;
1841 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001842 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1843 unsigned OpNum = 0;
1844 Value *Op;
1845 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1846 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001847 return Error("Invalid FREE record");
1848 I = new FreeInst(Op);
1849 break;
1850 }
1851 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1852 if (Record.size() < 3)
1853 return Error("Invalid ALLOCA record");
1854 const PointerType *Ty =
1855 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1856 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1857 unsigned Align = Record[2];
1858 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1859 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1860 break;
1861 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001862 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001863 unsigned OpNum = 0;
1864 Value *Op;
1865 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1866 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001867 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001868
1869 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001870 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001871 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001872 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1873 unsigned OpNum = 0;
1874 Value *Val, *Ptr;
1875 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1876 getValue(Record, OpNum,
1877 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1878 OpNum+2 != Record.size())
1879 return Error("Invalid STORE record");
1880
1881 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1882 break;
1883 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001884 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001885 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001886 unsigned OpNum = 0;
1887 Value *Val, *Ptr;
1888 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001889 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001890 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001891 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001892
1893 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001894 break;
1895 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001896 case bitc::FUNC_CODE_INST_CALL: {
1897 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1898 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001899 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001900
Devang Patel05988662008-09-25 21:00:45 +00001901 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001902 unsigned CCInfo = Record[1];
1903
1904 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001905 Value *Callee;
1906 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1907 return Error("Invalid CALL record");
1908
1909 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001910 const FunctionType *FTy = 0;
1911 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001912 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001913 return Error("Invalid CALL record");
1914
1915 SmallVector<Value*, 16> Args;
1916 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001917 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001918 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1919 Args.push_back(getBasicBlock(Record[OpNum]));
1920 else
1921 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001922 if (Args.back() == 0) return Error("Invalid CALL record");
1923 }
1924
Chris Lattner0579f7f2007-05-03 22:04:19 +00001925 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001926 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001927 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001928 return Error("Invalid CALL record");
1929 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001930 while (OpNum != Record.size()) {
1931 Value *Op;
1932 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1933 return Error("Invalid CALL record");
1934 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001935 }
1936 }
1937
Gabor Greif051a9502008-04-06 20:25:17 +00001938 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001939 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1940 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00001941 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001942 break;
1943 }
1944 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1945 if (Record.size() < 3)
1946 return Error("Invalid VAARG record");
1947 const Type *OpTy = getTypeByID(Record[0]);
1948 Value *Op = getFnValueByID(Record[1], OpTy);
1949 const Type *ResTy = getTypeByID(Record[2]);
1950 if (!OpTy || !Op || !ResTy)
1951 return Error("Invalid VAARG record");
1952 I = new VAArgInst(Op, ResTy);
1953 break;
1954 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001955 }
1956
1957 // Add instruction to end of current BB. If there is no current BB, reject
1958 // this file.
1959 if (CurBB == 0) {
1960 delete I;
1961 return Error("Invalid instruction with no BB");
1962 }
1963 CurBB->getInstList().push_back(I);
1964
1965 // If this was a terminator instruction, move to the next block.
1966 if (isa<TerminatorInst>(I)) {
1967 ++CurBBNo;
1968 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1969 }
1970
1971 // Non-void values get registered in the value table for future use.
1972 if (I && I->getType() != Type::VoidTy)
1973 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001974 }
1975
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001976 // Check the function list for unresolved values.
1977 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1978 if (A->getParent() == 0) {
1979 // We found at least one unresolved value. Nuke them all to avoid leaks.
1980 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1981 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1982 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1983 delete A;
1984 }
1985 }
Chris Lattner35a04702007-05-04 03:50:29 +00001986 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001987 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001988 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001989
1990 // Trim the value list down to the size it was before we parsed this function.
1991 ValueList.shrinkTo(ModuleValueListSize);
1992 std::vector<BasicBlock*>().swap(FunctionBBs);
1993
Chris Lattner48f84872007-05-01 04:59:48 +00001994 return false;
1995}
1996
Chris Lattnerb348bb82007-05-18 04:02:46 +00001997//===----------------------------------------------------------------------===//
1998// ModuleProvider implementation
1999//===----------------------------------------------------------------------===//
2000
2001
2002bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2003 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00002004 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002005
2006 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2007 DeferredFunctionInfo.find(F);
2008 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2009
2010 // Move the bit stream to the saved position of the deferred function body and
2011 // restore the real linkage type for the function.
2012 Stream.JumpToBit(DFII->second.first);
2013 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2014
2015 if (ParseFunctionBody(F)) {
2016 if (ErrInfo) *ErrInfo = ErrorString;
2017 return true;
2018 }
Chandler Carruth69940402007-08-04 01:51:18 +00002019
2020 // Upgrade any old intrinsic calls in the function.
2021 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2022 E = UpgradedIntrinsics.end(); I != E; ++I) {
2023 if (I->first != I->second) {
2024 for (Value::use_iterator UI = I->first->use_begin(),
2025 UE = I->first->use_end(); UI != UE; ) {
2026 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2027 UpgradeIntrinsicCall(CI, I->second);
2028 }
2029 }
2030 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00002031
2032 return false;
2033}
2034
2035void BitcodeReader::dematerializeFunction(Function *F) {
2036 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00002037 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00002038 return;
2039
2040 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2041
2042 // Just forget the function body, we can remat it later.
2043 F->deleteBody();
2044 F->setLinkage(GlobalValue::GhostLinkage);
2045}
2046
2047
2048Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2049 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
2050 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
2051 ++I) {
2052 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00002053 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00002054 materializeFunction(F, ErrInfo))
2055 return 0;
2056 }
Chandler Carruth69940402007-08-04 01:51:18 +00002057
2058 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2059 // delete the old functions to clean up. We can't do this unless the entire
2060 // module is materialized because there could always be another function body
2061 // with calls to the old function.
2062 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2063 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2064 if (I->first != I->second) {
2065 for (Value::use_iterator UI = I->first->use_begin(),
2066 UE = I->first->use_end(); UI != UE; ) {
2067 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2068 UpgradeIntrinsicCall(CI, I->second);
2069 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002070 if (!I->first->use_empty())
2071 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002072 I->first->eraseFromParent();
2073 }
2074 }
2075 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2076
Chris Lattnerb348bb82007-05-18 04:02:46 +00002077 return TheModule;
2078}
2079
2080
2081/// This method is provided by the parent ModuleProvde class and overriden
2082/// here. It simply releases the module from its provided and frees up our
2083/// state.
2084/// @brief Release our hold on the generated module
2085Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2086 // Since we're losing control of this Module, we must hand it back complete
2087 Module *M = ModuleProvider::releaseModule(ErrInfo);
2088 FreeState();
2089 return M;
2090}
2091
Chris Lattner48f84872007-05-01 04:59:48 +00002092
Chris Lattnerc453f762007-04-29 07:54:31 +00002093//===----------------------------------------------------------------------===//
2094// External interface
2095//===----------------------------------------------------------------------===//
2096
2097/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2098///
2099ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2100 std::string *ErrMsg) {
2101 BitcodeReader *R = new BitcodeReader(Buffer);
2102 if (R->ParseBitcode()) {
2103 if (ErrMsg)
2104 *ErrMsg = R->getErrorString();
2105
2106 // Don't let the BitcodeReader dtor delete 'Buffer'.
2107 R->releaseMemoryBuffer();
2108 delete R;
2109 return 0;
2110 }
2111 return R;
2112}
2113
2114/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2115/// If an error occurs, return null and fill in *ErrMsg if non-null.
2116Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2117 BitcodeReader *R;
2118 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2119 if (!R) return 0;
2120
Chris Lattnerb348bb82007-05-18 04:02:46 +00002121 // Read in the entire module.
2122 Module *M = R->materializeModule(ErrMsg);
2123
2124 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2125 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00002126 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002127
2128 // If there was no error, tell ModuleProvider not to delete it when its dtor
2129 // is run.
2130 if (M)
2131 M = R->releaseModule(ErrMsg);
2132
Chris Lattnerc453f762007-04-29 07:54:31 +00002133 delete R;
2134 return M;
2135}