1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 enum {
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
32 };
33
materializeForwardReferencedFunctions()34 void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
37 F->Materialize();
38 }
39 }
40
FreeState()41 void BitcodeReader::FreeState() {
42 if (BufferOwned)
43 delete Buffer;
44 Buffer = 0;
45 std::vector<Type*>().swap(TypeList);
46 ValueList.clear();
47 MDValueList.clear();
48
49 std::vector<AttributeSet>().swap(MAttributes);
50 std::vector<BasicBlock*>().swap(FunctionBBs);
51 std::vector<Function*>().swap(FunctionsWithBodies);
52 DeferredFunctionInfo.clear();
53 MDKindMap.clear();
54
55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
56 }
57
58 //===----------------------------------------------------------------------===//
59 // Helper functions to implement forward reference resolution, etc.
60 //===----------------------------------------------------------------------===//
61
62 /// ConvertToString - Convert a string from a record into an std::string, return
63 /// true on failure.
64 template<typename StrTy>
ConvertToString(ArrayRef<uint64_t> Record,unsigned Idx,StrTy & Result)65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
66 StrTy &Result) {
67 if (Idx > Record.size())
68 return true;
69
70 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71 Result += (char)Record[i];
72 return false;
73 }
74
GetDecodedLinkage(unsigned Val)75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
76 switch (Val) {
77 default: // Map unknown/new linkages to external
78 case 0: return GlobalValue::ExternalLinkage;
79 case 1: return GlobalValue::WeakAnyLinkage;
80 case 2: return GlobalValue::AppendingLinkage;
81 case 3: return GlobalValue::InternalLinkage;
82 case 4: return GlobalValue::LinkOnceAnyLinkage;
83 case 5: return GlobalValue::DLLImportLinkage;
84 case 6: return GlobalValue::DLLExportLinkage;
85 case 7: return GlobalValue::ExternalWeakLinkage;
86 case 8: return GlobalValue::CommonLinkage;
87 case 9: return GlobalValue::PrivateLinkage;
88 case 10: return GlobalValue::WeakODRLinkage;
89 case 11: return GlobalValue::LinkOnceODRLinkage;
90 case 12: return GlobalValue::AvailableExternallyLinkage;
91 case 13: return GlobalValue::LinkerPrivateLinkage;
92 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
93 }
94 }
95
GetDecodedVisibility(unsigned Val)96 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
97 switch (Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
101 case 2: return GlobalValue::ProtectedVisibility;
102 }
103 }
104
GetDecodedThreadLocalMode(unsigned Val)105 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
106 switch (Val) {
107 case 0: return GlobalVariable::NotThreadLocal;
108 default: // Map unknown non-zero value to general dynamic.
109 case 1: return GlobalVariable::GeneralDynamicTLSModel;
110 case 2: return GlobalVariable::LocalDynamicTLSModel;
111 case 3: return GlobalVariable::InitialExecTLSModel;
112 case 4: return GlobalVariable::LocalExecTLSModel;
113 }
114 }
115
GetDecodedCastOpcode(unsigned Val)116 static int GetDecodedCastOpcode(unsigned Val) {
117 switch (Val) {
118 default: return -1;
119 case bitc::CAST_TRUNC : return Instruction::Trunc;
120 case bitc::CAST_ZEXT : return Instruction::ZExt;
121 case bitc::CAST_SEXT : return Instruction::SExt;
122 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
123 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
124 case bitc::CAST_UITOFP : return Instruction::UIToFP;
125 case bitc::CAST_SITOFP : return Instruction::SIToFP;
126 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
127 case bitc::CAST_FPEXT : return Instruction::FPExt;
128 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
129 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
130 case bitc::CAST_BITCAST : return Instruction::BitCast;
131 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
132 }
133 }
GetDecodedBinaryOpcode(unsigned Val,Type * Ty)134 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
135 switch (Val) {
136 default: return -1;
137 case bitc::BINOP_ADD:
138 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
139 case bitc::BINOP_SUB:
140 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
141 case bitc::BINOP_MUL:
142 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
143 case bitc::BINOP_UDIV: return Instruction::UDiv;
144 case bitc::BINOP_SDIV:
145 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
146 case bitc::BINOP_UREM: return Instruction::URem;
147 case bitc::BINOP_SREM:
148 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
149 case bitc::BINOP_SHL: return Instruction::Shl;
150 case bitc::BINOP_LSHR: return Instruction::LShr;
151 case bitc::BINOP_ASHR: return Instruction::AShr;
152 case bitc::BINOP_AND: return Instruction::And;
153 case bitc::BINOP_OR: return Instruction::Or;
154 case bitc::BINOP_XOR: return Instruction::Xor;
155 }
156 }
157
GetDecodedRMWOperation(unsigned Val)158 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
159 switch (Val) {
160 default: return AtomicRMWInst::BAD_BINOP;
161 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
162 case bitc::RMW_ADD: return AtomicRMWInst::Add;
163 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
164 case bitc::RMW_AND: return AtomicRMWInst::And;
165 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
166 case bitc::RMW_OR: return AtomicRMWInst::Or;
167 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
168 case bitc::RMW_MAX: return AtomicRMWInst::Max;
169 case bitc::RMW_MIN: return AtomicRMWInst::Min;
170 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
171 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
172 }
173 }
174
GetDecodedOrdering(unsigned Val)175 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
176 switch (Val) {
177 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
178 case bitc::ORDERING_UNORDERED: return Unordered;
179 case bitc::ORDERING_MONOTONIC: return Monotonic;
180 case bitc::ORDERING_ACQUIRE: return Acquire;
181 case bitc::ORDERING_RELEASE: return Release;
182 case bitc::ORDERING_ACQREL: return AcquireRelease;
183 default: // Map unknown orderings to sequentially-consistent.
184 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
185 }
186 }
187
GetDecodedSynchScope(unsigned Val)188 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
189 switch (Val) {
190 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
191 default: // Map unknown scopes to cross-thread.
192 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
193 }
194 }
195
196 namespace llvm {
197 namespace {
198 /// @brief A class for maintaining the slot number definition
199 /// as a placeholder for the actual definition for forward constants defs.
200 class ConstantPlaceHolder : public ConstantExpr {
201 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
202 public:
203 // allocate space for exactly one operand
operator new(size_t s)204 void *operator new(size_t s) {
205 return User::operator new(s, 1);
206 }
ConstantPlaceHolder(Type * Ty,LLVMContext & Context)207 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
208 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
209 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
210 }
211
212 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
classof(const Value * V)213 static bool classof(const Value *V) {
214 return isa<ConstantExpr>(V) &&
215 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
216 }
217
218
219 /// Provide fast operand accessors
220 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
221 };
222 }
223
224 // FIXME: can we inherit this from ConstantExpr?
225 template <>
226 struct OperandTraits<ConstantPlaceHolder> :
227 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
228 };
229 }
230
231
AssignValue(Value * V,unsigned Idx)232 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
233 if (Idx == size()) {
234 push_back(V);
235 return;
236 }
237
238 if (Idx >= size())
239 resize(Idx+1);
240
241 WeakVH &OldV = ValuePtrs[Idx];
242 if (OldV == 0) {
243 OldV = V;
244 return;
245 }
246
247 // Handle constants and non-constants (e.g. instrs) differently for
248 // efficiency.
249 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
250 ResolveConstants.push_back(std::make_pair(PHC, Idx));
251 OldV = V;
252 } else {
253 // If there was a forward reference to this value, replace it.
254 Value *PrevVal = OldV;
255 OldV->replaceAllUsesWith(V);
256 delete PrevVal;
257 }
258 }
259
260
getConstantFwdRef(unsigned Idx,Type * Ty)261 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
262 Type *Ty) {
263 if (Idx >= size())
264 resize(Idx + 1);
265
266 if (Value *V = ValuePtrs[Idx]) {
267 assert(Ty == V->getType() && "Type mismatch in constant table!");
268 return cast<Constant>(V);
269 }
270
271 // Create and return a placeholder, which will later be RAUW'd.
272 Constant *C = new ConstantPlaceHolder(Ty, Context);
273 ValuePtrs[Idx] = C;
274 return C;
275 }
276
getValueFwdRef(unsigned Idx,Type * Ty)277 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
278 if (Idx >= size())
279 resize(Idx + 1);
280
281 if (Value *V = ValuePtrs[Idx]) {
282 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
283 return V;
284 }
285
286 // No type specified, must be invalid reference.
287 if (Ty == 0) return 0;
288
289 // Create and return a placeholder, which will later be RAUW'd.
290 Value *V = new Argument(Ty);
291 ValuePtrs[Idx] = V;
292 return V;
293 }
294
295 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
296 /// resolves any forward references. The idea behind this is that we sometimes
297 /// get constants (such as large arrays) which reference *many* forward ref
298 /// constants. Replacing each of these causes a lot of thrashing when
299 /// building/reuniquing the constant. Instead of doing this, we look at all the
300 /// uses and rewrite all the place holders at once for any constant that uses
301 /// a placeholder.
ResolveConstantForwardRefs()302 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
303 // Sort the values by-pointer so that they are efficient to look up with a
304 // binary search.
305 std::sort(ResolveConstants.begin(), ResolveConstants.end());
306
307 SmallVector<Constant*, 64> NewOps;
308
309 while (!ResolveConstants.empty()) {
310 Value *RealVal = operator[](ResolveConstants.back().second);
311 Constant *Placeholder = ResolveConstants.back().first;
312 ResolveConstants.pop_back();
313
314 // Loop over all users of the placeholder, updating them to reference the
315 // new value. If they reference more than one placeholder, update them all
316 // at once.
317 while (!Placeholder->use_empty()) {
318 Value::use_iterator UI = Placeholder->use_begin();
319 User *U = *UI;
320
321 // If the using object isn't uniqued, just update the operands. This
322 // handles instructions and initializers for global variables.
323 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
324 UI.getUse().set(RealVal);
325 continue;
326 }
327
328 // Otherwise, we have a constant that uses the placeholder. Replace that
329 // constant with a new constant that has *all* placeholder uses updated.
330 Constant *UserC = cast<Constant>(U);
331 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
332 I != E; ++I) {
333 Value *NewOp;
334 if (!isa<ConstantPlaceHolder>(*I)) {
335 // Not a placeholder reference.
336 NewOp = *I;
337 } else if (*I == Placeholder) {
338 // Common case is that it just references this one placeholder.
339 NewOp = RealVal;
340 } else {
341 // Otherwise, look up the placeholder in ResolveConstants.
342 ResolveConstantsTy::iterator It =
343 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
344 std::pair<Constant*, unsigned>(cast<Constant>(*I),
345 0));
346 assert(It != ResolveConstants.end() && It->first == *I);
347 NewOp = operator[](It->second);
348 }
349
350 NewOps.push_back(cast<Constant>(NewOp));
351 }
352
353 // Make the new constant.
354 Constant *NewC;
355 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
356 NewC = ConstantArray::get(UserCA->getType(), NewOps);
357 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
358 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
359 } else if (isa<ConstantVector>(UserC)) {
360 NewC = ConstantVector::get(NewOps);
361 } else {
362 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
363 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
364 }
365
366 UserC->replaceAllUsesWith(NewC);
367 UserC->destroyConstant();
368 NewOps.clear();
369 }
370
371 // Update all ValueHandles, they should be the only users at this point.
372 Placeholder->replaceAllUsesWith(RealVal);
373 delete Placeholder;
374 }
375 }
376
AssignValue(Value * V,unsigned Idx)377 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
378 if (Idx == size()) {
379 push_back(V);
380 return;
381 }
382
383 if (Idx >= size())
384 resize(Idx+1);
385
386 WeakVH &OldV = MDValuePtrs[Idx];
387 if (OldV == 0) {
388 OldV = V;
389 return;
390 }
391
392 // If there was a forward reference to this value, replace it.
393 MDNode *PrevVal = cast<MDNode>(OldV);
394 OldV->replaceAllUsesWith(V);
395 MDNode::deleteTemporary(PrevVal);
396 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
397 // value for Idx.
398 MDValuePtrs[Idx] = V;
399 }
400
getValueFwdRef(unsigned Idx)401 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
402 if (Idx >= size())
403 resize(Idx + 1);
404
405 if (Value *V = MDValuePtrs[Idx]) {
406 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
407 return V;
408 }
409
410 // Create and return a placeholder, which will later be RAUW'd.
411 Value *V = MDNode::getTemporary(Context, None);
412 MDValuePtrs[Idx] = V;
413 return V;
414 }
415
getTypeByID(unsigned ID)416 Type *BitcodeReader::getTypeByID(unsigned ID) {
417 // The type table size is always specified correctly.
418 if (ID >= TypeList.size())
419 return 0;
420
421 if (Type *Ty = TypeList[ID])
422 return Ty;
423
424 // If we have a forward reference, the only possible case is when it is to a
425 // named struct. Just create a placeholder for now.
426 return TypeList[ID] = StructType::create(Context);
427 }
428
429
430 //===----------------------------------------------------------------------===//
431 // Functions for parsing blocks from the bitcode file
432 //===----------------------------------------------------------------------===//
433
434
435 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
436 /// been decoded from the given integer. This function must stay in sync with
437 /// 'encodeLLVMAttributesForBitcode'.
decodeLLVMAttributesForBitcode(AttrBuilder & B,uint64_t EncodedAttrs)438 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
439 uint64_t EncodedAttrs) {
440 // FIXME: Remove in 4.0.
441
442 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
443 // the bits above 31 down by 11 bits.
444 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
445 assert((!Alignment || isPowerOf2_32(Alignment)) &&
446 "Alignment must be a power of two.");
447
448 if (Alignment)
449 B.addAlignmentAttr(Alignment);
450 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
451 (EncodedAttrs & 0xffff));
452 }
453
ParseAttributeBlock()454 error_code BitcodeReader::ParseAttributeBlock() {
455 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
456 return Error(InvalidRecord);
457
458 if (!MAttributes.empty())
459 return Error(InvalidMultipleBlocks);
460
461 SmallVector<uint64_t, 64> Record;
462
463 SmallVector<AttributeSet, 8> Attrs;
464
465 // Read all the records.
466 while (1) {
467 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
468
469 switch (Entry.Kind) {
470 case BitstreamEntry::SubBlock: // Handled for us already.
471 case BitstreamEntry::Error:
472 return Error(MalformedBlock);
473 case BitstreamEntry::EndBlock:
474 return error_code::success();
475 case BitstreamEntry::Record:
476 // The interesting case.
477 break;
478 }
479
480 // Read a record.
481 Record.clear();
482 switch (Stream.readRecord(Entry.ID, Record)) {
483 default: // Default behavior: ignore.
484 break;
485 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
486 // FIXME: Remove in 4.0.
487 if (Record.size() & 1)
488 return Error(InvalidRecord);
489
490 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
491 AttrBuilder B;
492 decodeLLVMAttributesForBitcode(B, Record[i+1]);
493 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
494 }
495
496 MAttributes.push_back(AttributeSet::get(Context, Attrs));
497 Attrs.clear();
498 break;
499 }
500 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
501 for (unsigned i = 0, e = Record.size(); i != e; ++i)
502 Attrs.push_back(MAttributeGroups[Record[i]]);
503
504 MAttributes.push_back(AttributeSet::get(Context, Attrs));
505 Attrs.clear();
506 break;
507 }
508 }
509 }
510 }
511
512 // Returns Attribute::None on unrecognized codes.
GetAttrFromCode(uint64_t Code)513 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
514 switch (Code) {
515 default:
516 return Attribute::None;
517 case bitc::ATTR_KIND_ALIGNMENT:
518 return Attribute::Alignment;
519 case bitc::ATTR_KIND_ALWAYS_INLINE:
520 return Attribute::AlwaysInline;
521 case bitc::ATTR_KIND_BUILTIN:
522 return Attribute::Builtin;
523 case bitc::ATTR_KIND_BY_VAL:
524 return Attribute::ByVal;
525 case bitc::ATTR_KIND_COLD:
526 return Attribute::Cold;
527 case bitc::ATTR_KIND_INLINE_HINT:
528 return Attribute::InlineHint;
529 case bitc::ATTR_KIND_IN_REG:
530 return Attribute::InReg;
531 case bitc::ATTR_KIND_MIN_SIZE:
532 return Attribute::MinSize;
533 case bitc::ATTR_KIND_NAKED:
534 return Attribute::Naked;
535 case bitc::ATTR_KIND_NEST:
536 return Attribute::Nest;
537 case bitc::ATTR_KIND_NO_ALIAS:
538 return Attribute::NoAlias;
539 case bitc::ATTR_KIND_NO_BUILTIN:
540 return Attribute::NoBuiltin;
541 case bitc::ATTR_KIND_NO_CAPTURE:
542 return Attribute::NoCapture;
543 case bitc::ATTR_KIND_NO_DUPLICATE:
544 return Attribute::NoDuplicate;
545 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
546 return Attribute::NoImplicitFloat;
547 case bitc::ATTR_KIND_NO_INLINE:
548 return Attribute::NoInline;
549 case bitc::ATTR_KIND_NON_LAZY_BIND:
550 return Attribute::NonLazyBind;
551 case bitc::ATTR_KIND_NO_RED_ZONE:
552 return Attribute::NoRedZone;
553 case bitc::ATTR_KIND_NO_RETURN:
554 return Attribute::NoReturn;
555 case bitc::ATTR_KIND_NO_UNWIND:
556 return Attribute::NoUnwind;
557 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
558 return Attribute::OptimizeForSize;
559 case bitc::ATTR_KIND_OPTIMIZE_NONE:
560 return Attribute::OptimizeNone;
561 case bitc::ATTR_KIND_READ_NONE:
562 return Attribute::ReadNone;
563 case bitc::ATTR_KIND_READ_ONLY:
564 return Attribute::ReadOnly;
565 case bitc::ATTR_KIND_RETURNED:
566 return Attribute::Returned;
567 case bitc::ATTR_KIND_RETURNS_TWICE:
568 return Attribute::ReturnsTwice;
569 case bitc::ATTR_KIND_S_EXT:
570 return Attribute::SExt;
571 case bitc::ATTR_KIND_STACK_ALIGNMENT:
572 return Attribute::StackAlignment;
573 case bitc::ATTR_KIND_STACK_PROTECT:
574 return Attribute::StackProtect;
575 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
576 return Attribute::StackProtectReq;
577 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
578 return Attribute::StackProtectStrong;
579 case bitc::ATTR_KIND_STRUCT_RET:
580 return Attribute::StructRet;
581 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
582 return Attribute::SanitizeAddress;
583 case bitc::ATTR_KIND_SANITIZE_THREAD:
584 return Attribute::SanitizeThread;
585 case bitc::ATTR_KIND_SANITIZE_MEMORY:
586 return Attribute::SanitizeMemory;
587 case bitc::ATTR_KIND_UW_TABLE:
588 return Attribute::UWTable;
589 case bitc::ATTR_KIND_Z_EXT:
590 return Attribute::ZExt;
591 }
592 }
593
ParseAttrKind(uint64_t Code,Attribute::AttrKind * Kind)594 error_code BitcodeReader::ParseAttrKind(uint64_t Code,
595 Attribute::AttrKind *Kind) {
596 *Kind = GetAttrFromCode(Code);
597 if (*Kind == Attribute::None)
598 return Error(InvalidValue);
599 return error_code::success();
600 }
601
ParseAttributeGroupBlock()602 error_code BitcodeReader::ParseAttributeGroupBlock() {
603 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
604 return Error(InvalidRecord);
605
606 if (!MAttributeGroups.empty())
607 return Error(InvalidMultipleBlocks);
608
609 SmallVector<uint64_t, 64> Record;
610
611 // Read all the records.
612 while (1) {
613 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
614
615 switch (Entry.Kind) {
616 case BitstreamEntry::SubBlock: // Handled for us already.
617 case BitstreamEntry::Error:
618 return Error(MalformedBlock);
619 case BitstreamEntry::EndBlock:
620 return error_code::success();
621 case BitstreamEntry::Record:
622 // The interesting case.
623 break;
624 }
625
626 // Read a record.
627 Record.clear();
628 switch (Stream.readRecord(Entry.ID, Record)) {
629 default: // Default behavior: ignore.
630 break;
631 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
632 if (Record.size() < 3)
633 return Error(InvalidRecord);
634
635 uint64_t GrpID = Record[0];
636 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
637
638 AttrBuilder B;
639 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
640 if (Record[i] == 0) { // Enum attribute
641 Attribute::AttrKind Kind;
642 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
643 return EC;
644
645 B.addAttribute(Kind);
646 } else if (Record[i] == 1) { // Align attribute
647 Attribute::AttrKind Kind;
648 if (error_code EC = ParseAttrKind(Record[++i], &Kind))
649 return EC;
650 if (Kind == Attribute::Alignment)
651 B.addAlignmentAttr(Record[++i]);
652 else
653 B.addStackAlignmentAttr(Record[++i]);
654 } else { // String attribute
655 assert((Record[i] == 3 || Record[i] == 4) &&
656 "Invalid attribute group entry");
657 bool HasValue = (Record[i++] == 4);
658 SmallString<64> KindStr;
659 SmallString<64> ValStr;
660
661 while (Record[i] != 0 && i != e)
662 KindStr += Record[i++];
663 assert(Record[i] == 0 && "Kind string not null terminated");
664
665 if (HasValue) {
666 // Has a value associated with it.
667 ++i; // Skip the '0' that terminates the "kind" string.
668 while (Record[i] != 0 && i != e)
669 ValStr += Record[i++];
670 assert(Record[i] == 0 && "Value string not null terminated");
671 }
672
673 B.addAttribute(KindStr.str(), ValStr.str());
674 }
675 }
676
677 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
678 break;
679 }
680 }
681 }
682 }
683
ParseTypeTable()684 error_code BitcodeReader::ParseTypeTable() {
685 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
686 return Error(InvalidRecord);
687
688 return ParseTypeTableBody();
689 }
690
ParseTypeTableBody()691 error_code BitcodeReader::ParseTypeTableBody() {
692 if (!TypeList.empty())
693 return Error(InvalidMultipleBlocks);
694
695 SmallVector<uint64_t, 64> Record;
696 unsigned NumRecords = 0;
697
698 SmallString<64> TypeName;
699
700 // Read all the records for this type table.
701 while (1) {
702 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
703
704 switch (Entry.Kind) {
705 case BitstreamEntry::SubBlock: // Handled for us already.
706 case BitstreamEntry::Error:
707 return Error(MalformedBlock);
708 case BitstreamEntry::EndBlock:
709 if (NumRecords != TypeList.size())
710 return Error(MalformedBlock);
711 return error_code::success();
712 case BitstreamEntry::Record:
713 // The interesting case.
714 break;
715 }
716
717 // Read a record.
718 Record.clear();
719 Type *ResultTy = 0;
720 switch (Stream.readRecord(Entry.ID, Record)) {
721 default:
722 return Error(InvalidValue);
723 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
724 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
725 // type list. This allows us to reserve space.
726 if (Record.size() < 1)
727 return Error(InvalidRecord);
728 TypeList.resize(Record[0]);
729 continue;
730 case bitc::TYPE_CODE_VOID: // VOID
731 ResultTy = Type::getVoidTy(Context);
732 break;
733 case bitc::TYPE_CODE_HALF: // HALF
734 ResultTy = Type::getHalfTy(Context);
735 break;
736 case bitc::TYPE_CODE_FLOAT: // FLOAT
737 ResultTy = Type::getFloatTy(Context);
738 break;
739 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
740 ResultTy = Type::getDoubleTy(Context);
741 break;
742 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
743 ResultTy = Type::getX86_FP80Ty(Context);
744 break;
745 case bitc::TYPE_CODE_FP128: // FP128
746 ResultTy = Type::getFP128Ty(Context);
747 break;
748 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
749 ResultTy = Type::getPPC_FP128Ty(Context);
750 break;
751 case bitc::TYPE_CODE_LABEL: // LABEL
752 ResultTy = Type::getLabelTy(Context);
753 break;
754 case bitc::TYPE_CODE_METADATA: // METADATA
755 ResultTy = Type::getMetadataTy(Context);
756 break;
757 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
758 ResultTy = Type::getX86_MMXTy(Context);
759 break;
760 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
761 if (Record.size() < 1)
762 return Error(InvalidRecord);
763
764 ResultTy = IntegerType::get(Context, Record[0]);
765 break;
766 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
767 // [pointee type, address space]
768 if (Record.size() < 1)
769 return Error(InvalidRecord);
770 unsigned AddressSpace = 0;
771 if (Record.size() == 2)
772 AddressSpace = Record[1];
773 ResultTy = getTypeByID(Record[0]);
774 if (ResultTy == 0)
775 return Error(InvalidType);
776 ResultTy = PointerType::get(ResultTy, AddressSpace);
777 break;
778 }
779 case bitc::TYPE_CODE_FUNCTION_OLD: {
780 // FIXME: attrid is dead, remove it in LLVM 4.0
781 // FUNCTION: [vararg, attrid, retty, paramty x N]
782 if (Record.size() < 3)
783 return Error(InvalidRecord);
784 SmallVector<Type*, 8> ArgTys;
785 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
786 if (Type *T = getTypeByID(Record[i]))
787 ArgTys.push_back(T);
788 else
789 break;
790 }
791
792 ResultTy = getTypeByID(Record[2]);
793 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
794 return Error(InvalidType);
795
796 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
797 break;
798 }
799 case bitc::TYPE_CODE_FUNCTION: {
800 // FUNCTION: [vararg, retty, paramty x N]
801 if (Record.size() < 2)
802 return Error(InvalidRecord);
803 SmallVector<Type*, 8> ArgTys;
804 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
805 if (Type *T = getTypeByID(Record[i]))
806 ArgTys.push_back(T);
807 else
808 break;
809 }
810
811 ResultTy = getTypeByID(Record[1]);
812 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
813 return Error(InvalidType);
814
815 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
816 break;
817 }
818 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
819 if (Record.size() < 1)
820 return Error(InvalidRecord);
821 SmallVector<Type*, 8> EltTys;
822 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
823 if (Type *T = getTypeByID(Record[i]))
824 EltTys.push_back(T);
825 else
826 break;
827 }
828 if (EltTys.size() != Record.size()-1)
829 return Error(InvalidType);
830 ResultTy = StructType::get(Context, EltTys, Record[0]);
831 break;
832 }
833 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
834 if (ConvertToString(Record, 0, TypeName))
835 return Error(InvalidRecord);
836 continue;
837
838 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
839 if (Record.size() < 1)
840 return Error(InvalidRecord);
841
842 if (NumRecords >= TypeList.size())
843 return Error(InvalidTYPETable);
844
845 // Check to see if this was forward referenced, if so fill in the temp.
846 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
847 if (Res) {
848 Res->setName(TypeName);
849 TypeList[NumRecords] = 0;
850 } else // Otherwise, create a new struct.
851 Res = StructType::create(Context, TypeName);
852 TypeName.clear();
853
854 SmallVector<Type*, 8> EltTys;
855 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
856 if (Type *T = getTypeByID(Record[i]))
857 EltTys.push_back(T);
858 else
859 break;
860 }
861 if (EltTys.size() != Record.size()-1)
862 return Error(InvalidRecord);
863 Res->setBody(EltTys, Record[0]);
864 ResultTy = Res;
865 break;
866 }
867 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
868 if (Record.size() != 1)
869 return Error(InvalidRecord);
870
871 if (NumRecords >= TypeList.size())
872 return Error(InvalidTYPETable);
873
874 // Check to see if this was forward referenced, if so fill in the temp.
875 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
876 if (Res) {
877 Res->setName(TypeName);
878 TypeList[NumRecords] = 0;
879 } else // Otherwise, create a new struct with no body.
880 Res = StructType::create(Context, TypeName);
881 TypeName.clear();
882 ResultTy = Res;
883 break;
884 }
885 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
886 if (Record.size() < 2)
887 return Error(InvalidRecord);
888 if ((ResultTy = getTypeByID(Record[1])))
889 ResultTy = ArrayType::get(ResultTy, Record[0]);
890 else
891 return Error(InvalidType);
892 break;
893 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
894 if (Record.size() < 2)
895 return Error(InvalidRecord);
896 if ((ResultTy = getTypeByID(Record[1])))
897 ResultTy = VectorType::get(ResultTy, Record[0]);
898 else
899 return Error(InvalidType);
900 break;
901 }
902
903 if (NumRecords >= TypeList.size())
904 return Error(InvalidTYPETable);
905 assert(ResultTy && "Didn't read a type?");
906 assert(TypeList[NumRecords] == 0 && "Already read type?");
907 TypeList[NumRecords++] = ResultTy;
908 }
909 }
910
ParseValueSymbolTable()911 error_code BitcodeReader::ParseValueSymbolTable() {
912 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
913 return Error(InvalidRecord);
914
915 SmallVector<uint64_t, 64> Record;
916
917 // Read all the records for this value table.
918 SmallString<128> ValueName;
919 while (1) {
920 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
921
922 switch (Entry.Kind) {
923 case BitstreamEntry::SubBlock: // Handled for us already.
924 case BitstreamEntry::Error:
925 return Error(MalformedBlock);
926 case BitstreamEntry::EndBlock:
927 return error_code::success();
928 case BitstreamEntry::Record:
929 // The interesting case.
930 break;
931 }
932
933 // Read a record.
934 Record.clear();
935 switch (Stream.readRecord(Entry.ID, Record)) {
936 default: // Default behavior: unknown type.
937 break;
938 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
939 if (ConvertToString(Record, 1, ValueName))
940 return Error(InvalidRecord);
941 unsigned ValueID = Record[0];
942 if (ValueID >= ValueList.size())
943 return Error(InvalidRecord);
944 Value *V = ValueList[ValueID];
945
946 V->setName(StringRef(ValueName.data(), ValueName.size()));
947 ValueName.clear();
948 break;
949 }
950 case bitc::VST_CODE_BBENTRY: {
951 if (ConvertToString(Record, 1, ValueName))
952 return Error(InvalidRecord);
953 BasicBlock *BB = getBasicBlock(Record[0]);
954 if (BB == 0)
955 return Error(InvalidRecord);
956
957 BB->setName(StringRef(ValueName.data(), ValueName.size()));
958 ValueName.clear();
959 break;
960 }
961 }
962 }
963 }
964
ParseMetadata()965 error_code BitcodeReader::ParseMetadata() {
966 unsigned NextMDValueNo = MDValueList.size();
967
968 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
969 return Error(InvalidRecord);
970
971 SmallVector<uint64_t, 64> Record;
972
973 // Read all the records.
974 while (1) {
975 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
976
977 switch (Entry.Kind) {
978 case BitstreamEntry::SubBlock: // Handled for us already.
979 case BitstreamEntry::Error:
980 return Error(MalformedBlock);
981 case BitstreamEntry::EndBlock:
982 return error_code::success();
983 case BitstreamEntry::Record:
984 // The interesting case.
985 break;
986 }
987
988 bool IsFunctionLocal = false;
989 // Read a record.
990 Record.clear();
991 unsigned Code = Stream.readRecord(Entry.ID, Record);
992 switch (Code) {
993 default: // Default behavior: ignore.
994 break;
995 case bitc::METADATA_NAME: {
996 // Read name of the named metadata.
997 SmallString<8> Name(Record.begin(), Record.end());
998 Record.clear();
999 Code = Stream.ReadCode();
1000
1001 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1002 unsigned NextBitCode = Stream.readRecord(Code, Record);
1003 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1004
1005 // Read named metadata elements.
1006 unsigned Size = Record.size();
1007 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1008 for (unsigned i = 0; i != Size; ++i) {
1009 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1010 if (MD == 0)
1011 return Error(InvalidRecord);
1012 NMD->addOperand(MD);
1013 }
1014 break;
1015 }
1016 case bitc::METADATA_FN_NODE:
1017 IsFunctionLocal = true;
1018 // fall-through
1019 case bitc::METADATA_NODE: {
1020 if (Record.size() % 2 == 1)
1021 return Error(InvalidRecord);
1022
1023 unsigned Size = Record.size();
1024 SmallVector<Value*, 8> Elts;
1025 for (unsigned i = 0; i != Size; i += 2) {
1026 Type *Ty = getTypeByID(Record[i]);
1027 if (!Ty)
1028 return Error(InvalidRecord);
1029 if (Ty->isMetadataTy())
1030 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1031 else if (!Ty->isVoidTy())
1032 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1033 else
1034 Elts.push_back(NULL);
1035 }
1036 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1037 IsFunctionLocal = false;
1038 MDValueList.AssignValue(V, NextMDValueNo++);
1039 break;
1040 }
1041 case bitc::METADATA_STRING: {
1042 SmallString<8> String(Record.begin(), Record.end());
1043 Value *V = MDString::get(Context, String);
1044 MDValueList.AssignValue(V, NextMDValueNo++);
1045 break;
1046 }
1047 case bitc::METADATA_KIND: {
1048 if (Record.size() < 2)
1049 return Error(InvalidRecord);
1050
1051 unsigned Kind = Record[0];
1052 SmallString<8> Name(Record.begin()+1, Record.end());
1053
1054 unsigned NewKind = TheModule->getMDKindID(Name.str());
1055 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1056 return Error(ConflictingMETADATA_KINDRecords);
1057 break;
1058 }
1059 }
1060 }
1061 }
1062
1063 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1064 /// the LSB for dense VBR encoding.
decodeSignRotatedValue(uint64_t V)1065 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1066 if ((V & 1) == 0)
1067 return V >> 1;
1068 if (V != 1)
1069 return -(V >> 1);
1070 // There is no such thing as -0 with integers. "-0" really means MININT.
1071 return 1ULL << 63;
1072 }
1073
1074 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1075 /// values and aliases that we can.
ResolveGlobalAndAliasInits()1076 error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1077 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1078 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1079 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1080
1081 GlobalInitWorklist.swap(GlobalInits);
1082 AliasInitWorklist.swap(AliasInits);
1083 FunctionPrefixWorklist.swap(FunctionPrefixes);
1084
1085 while (!GlobalInitWorklist.empty()) {
1086 unsigned ValID = GlobalInitWorklist.back().second;
1087 if (ValID >= ValueList.size()) {
1088 // Not ready to resolve this yet, it requires something later in the file.
1089 GlobalInits.push_back(GlobalInitWorklist.back());
1090 } else {
1091 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1092 GlobalInitWorklist.back().first->setInitializer(C);
1093 else
1094 return Error(ExpectedConstant);
1095 }
1096 GlobalInitWorklist.pop_back();
1097 }
1098
1099 while (!AliasInitWorklist.empty()) {
1100 unsigned ValID = AliasInitWorklist.back().second;
1101 if (ValID >= ValueList.size()) {
1102 AliasInits.push_back(AliasInitWorklist.back());
1103 } else {
1104 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1105 AliasInitWorklist.back().first->setAliasee(C);
1106 else
1107 return Error(ExpectedConstant);
1108 }
1109 AliasInitWorklist.pop_back();
1110 }
1111
1112 while (!FunctionPrefixWorklist.empty()) {
1113 unsigned ValID = FunctionPrefixWorklist.back().second;
1114 if (ValID >= ValueList.size()) {
1115 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1116 } else {
1117 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1118 FunctionPrefixWorklist.back().first->setPrefixData(C);
1119 else
1120 return Error(ExpectedConstant);
1121 }
1122 FunctionPrefixWorklist.pop_back();
1123 }
1124
1125 return error_code::success();
1126 }
1127
ReadWideAPInt(ArrayRef<uint64_t> Vals,unsigned TypeBits)1128 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1129 SmallVector<uint64_t, 8> Words(Vals.size());
1130 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1131 BitcodeReader::decodeSignRotatedValue);
1132
1133 return APInt(TypeBits, Words);
1134 }
1135
ParseConstants()1136 error_code BitcodeReader::ParseConstants() {
1137 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1138 return Error(InvalidRecord);
1139
1140 SmallVector<uint64_t, 64> Record;
1141
1142 // Read all the records for this value table.
1143 Type *CurTy = Type::getInt32Ty(Context);
1144 unsigned NextCstNo = ValueList.size();
1145 while (1) {
1146 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1147
1148 switch (Entry.Kind) {
1149 case BitstreamEntry::SubBlock: // Handled for us already.
1150 case BitstreamEntry::Error:
1151 return Error(MalformedBlock);
1152 case BitstreamEntry::EndBlock:
1153 if (NextCstNo != ValueList.size())
1154 return Error(InvalidConstantReference);
1155
1156 // Once all the constants have been read, go through and resolve forward
1157 // references.
1158 ValueList.ResolveConstantForwardRefs();
1159 return error_code::success();
1160 case BitstreamEntry::Record:
1161 // The interesting case.
1162 break;
1163 }
1164
1165 // Read a record.
1166 Record.clear();
1167 Value *V = 0;
1168 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1169 switch (BitCode) {
1170 default: // Default behavior: unknown constant
1171 case bitc::CST_CODE_UNDEF: // UNDEF
1172 V = UndefValue::get(CurTy);
1173 break;
1174 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1175 if (Record.empty())
1176 return Error(InvalidRecord);
1177 if (Record[0] >= TypeList.size())
1178 return Error(InvalidRecord);
1179 CurTy = TypeList[Record[0]];
1180 continue; // Skip the ValueList manipulation.
1181 case bitc::CST_CODE_NULL: // NULL
1182 V = Constant::getNullValue(CurTy);
1183 break;
1184 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1185 if (!CurTy->isIntegerTy() || Record.empty())
1186 return Error(InvalidRecord);
1187 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1188 break;
1189 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1190 if (!CurTy->isIntegerTy() || Record.empty())
1191 return Error(InvalidRecord);
1192
1193 APInt VInt = ReadWideAPInt(Record,
1194 cast<IntegerType>(CurTy)->getBitWidth());
1195 V = ConstantInt::get(Context, VInt);
1196
1197 break;
1198 }
1199 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1200 if (Record.empty())
1201 return Error(InvalidRecord);
1202 if (CurTy->isHalfTy())
1203 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1204 APInt(16, (uint16_t)Record[0])));
1205 else if (CurTy->isFloatTy())
1206 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1207 APInt(32, (uint32_t)Record[0])));
1208 else if (CurTy->isDoubleTy())
1209 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1210 APInt(64, Record[0])));
1211 else if (CurTy->isX86_FP80Ty()) {
1212 // Bits are not stored the same way as a normal i80 APInt, compensate.
1213 uint64_t Rearrange[2];
1214 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1215 Rearrange[1] = Record[0] >> 48;
1216 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1217 APInt(80, Rearrange)));
1218 } else if (CurTy->isFP128Ty())
1219 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1220 APInt(128, Record)));
1221 else if (CurTy->isPPC_FP128Ty())
1222 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1223 APInt(128, Record)));
1224 else
1225 V = UndefValue::get(CurTy);
1226 break;
1227 }
1228
1229 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1230 if (Record.empty())
1231 return Error(InvalidRecord);
1232
1233 unsigned Size = Record.size();
1234 SmallVector<Constant*, 16> Elts;
1235
1236 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1237 for (unsigned i = 0; i != Size; ++i)
1238 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1239 STy->getElementType(i)));
1240 V = ConstantStruct::get(STy, Elts);
1241 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1242 Type *EltTy = ATy->getElementType();
1243 for (unsigned i = 0; i != Size; ++i)
1244 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1245 V = ConstantArray::get(ATy, Elts);
1246 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1247 Type *EltTy = VTy->getElementType();
1248 for (unsigned i = 0; i != Size; ++i)
1249 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1250 V = ConstantVector::get(Elts);
1251 } else {
1252 V = UndefValue::get(CurTy);
1253 }
1254 break;
1255 }
1256 case bitc::CST_CODE_STRING: // STRING: [values]
1257 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1258 if (Record.empty())
1259 return Error(InvalidRecord);
1260
1261 SmallString<16> Elts(Record.begin(), Record.end());
1262 V = ConstantDataArray::getString(Context, Elts,
1263 BitCode == bitc::CST_CODE_CSTRING);
1264 break;
1265 }
1266 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1267 if (Record.empty())
1268 return Error(InvalidRecord);
1269
1270 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1271 unsigned Size = Record.size();
1272
1273 if (EltTy->isIntegerTy(8)) {
1274 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1275 if (isa<VectorType>(CurTy))
1276 V = ConstantDataVector::get(Context, Elts);
1277 else
1278 V = ConstantDataArray::get(Context, Elts);
1279 } else if (EltTy->isIntegerTy(16)) {
1280 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1281 if (isa<VectorType>(CurTy))
1282 V = ConstantDataVector::get(Context, Elts);
1283 else
1284 V = ConstantDataArray::get(Context, Elts);
1285 } else if (EltTy->isIntegerTy(32)) {
1286 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1287 if (isa<VectorType>(CurTy))
1288 V = ConstantDataVector::get(Context, Elts);
1289 else
1290 V = ConstantDataArray::get(Context, Elts);
1291 } else if (EltTy->isIntegerTy(64)) {
1292 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1293 if (isa<VectorType>(CurTy))
1294 V = ConstantDataVector::get(Context, Elts);
1295 else
1296 V = ConstantDataArray::get(Context, Elts);
1297 } else if (EltTy->isFloatTy()) {
1298 SmallVector<float, 16> Elts(Size);
1299 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1300 if (isa<VectorType>(CurTy))
1301 V = ConstantDataVector::get(Context, Elts);
1302 else
1303 V = ConstantDataArray::get(Context, Elts);
1304 } else if (EltTy->isDoubleTy()) {
1305 SmallVector<double, 16> Elts(Size);
1306 std::transform(Record.begin(), Record.end(), Elts.begin(),
1307 BitsToDouble);
1308 if (isa<VectorType>(CurTy))
1309 V = ConstantDataVector::get(Context, Elts);
1310 else
1311 V = ConstantDataArray::get(Context, Elts);
1312 } else {
1313 return Error(InvalidTypeForValue);
1314 }
1315 break;
1316 }
1317
1318 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1319 if (Record.size() < 3)
1320 return Error(InvalidRecord);
1321 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1322 if (Opc < 0) {
1323 V = UndefValue::get(CurTy); // Unknown binop.
1324 } else {
1325 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1326 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1327 unsigned Flags = 0;
1328 if (Record.size() >= 4) {
1329 if (Opc == Instruction::Add ||
1330 Opc == Instruction::Sub ||
1331 Opc == Instruction::Mul ||
1332 Opc == Instruction::Shl) {
1333 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1334 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1335 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1336 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1337 } else if (Opc == Instruction::SDiv ||
1338 Opc == Instruction::UDiv ||
1339 Opc == Instruction::LShr ||
1340 Opc == Instruction::AShr) {
1341 if (Record[3] & (1 << bitc::PEO_EXACT))
1342 Flags |= SDivOperator::IsExact;
1343 }
1344 }
1345 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1346 }
1347 break;
1348 }
1349 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1350 if (Record.size() < 3)
1351 return Error(InvalidRecord);
1352 int Opc = GetDecodedCastOpcode(Record[0]);
1353 if (Opc < 0) {
1354 V = UndefValue::get(CurTy); // Unknown cast.
1355 } else {
1356 Type *OpTy = getTypeByID(Record[1]);
1357 if (!OpTy)
1358 return Error(InvalidRecord);
1359 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1360 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1361 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1362 }
1363 break;
1364 }
1365 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1366 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1367 if (Record.size() & 1)
1368 return Error(InvalidRecord);
1369 SmallVector<Constant*, 16> Elts;
1370 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1371 Type *ElTy = getTypeByID(Record[i]);
1372 if (!ElTy)
1373 return Error(InvalidRecord);
1374 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1375 }
1376 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1377 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1378 BitCode ==
1379 bitc::CST_CODE_CE_INBOUNDS_GEP);
1380 break;
1381 }
1382 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1383 if (Record.size() < 3)
1384 return Error(InvalidRecord);
1385
1386 Type *SelectorTy = Type::getInt1Ty(Context);
1387
1388 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1389 // vector. Otherwise, it must be a single bit.
1390 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1391 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1392 VTy->getNumElements());
1393
1394 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1395 SelectorTy),
1396 ValueList.getConstantFwdRef(Record[1],CurTy),
1397 ValueList.getConstantFwdRef(Record[2],CurTy));
1398 break;
1399 }
1400 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1401 if (Record.size() < 3)
1402 return Error(InvalidRecord);
1403 VectorType *OpTy =
1404 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1405 if (OpTy == 0)
1406 return Error(InvalidRecord);
1407 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1408 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1409 Type::getInt32Ty(Context));
1410 V = ConstantExpr::getExtractElement(Op0, Op1);
1411 break;
1412 }
1413 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1414 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1415 if (Record.size() < 3 || OpTy == 0)
1416 return Error(InvalidRecord);
1417 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1418 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1419 OpTy->getElementType());
1420 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1421 Type::getInt32Ty(Context));
1422 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1423 break;
1424 }
1425 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1426 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1427 if (Record.size() < 3 || OpTy == 0)
1428 return Error(InvalidRecord);
1429 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1430 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1431 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1432 OpTy->getNumElements());
1433 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1434 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1435 break;
1436 }
1437 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1438 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1439 VectorType *OpTy =
1440 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1441 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1442 return Error(InvalidRecord);
1443 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1444 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1445 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1446 RTy->getNumElements());
1447 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1448 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1449 break;
1450 }
1451 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1452 if (Record.size() < 4)
1453 return Error(InvalidRecord);
1454 Type *OpTy = getTypeByID(Record[0]);
1455 if (OpTy == 0)
1456 return Error(InvalidRecord);
1457 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1458 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1459
1460 if (OpTy->isFPOrFPVectorTy())
1461 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1462 else
1463 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1464 break;
1465 }
1466 // This maintains backward compatibility, pre-asm dialect keywords.
1467 // FIXME: Remove with the 4.0 release.
1468 case bitc::CST_CODE_INLINEASM_OLD: {
1469 if (Record.size() < 2)
1470 return Error(InvalidRecord);
1471 std::string AsmStr, ConstrStr;
1472 bool HasSideEffects = Record[0] & 1;
1473 bool IsAlignStack = Record[0] >> 1;
1474 unsigned AsmStrSize = Record[1];
1475 if (2+AsmStrSize >= Record.size())
1476 return Error(InvalidRecord);
1477 unsigned ConstStrSize = Record[2+AsmStrSize];
1478 if (3+AsmStrSize+ConstStrSize > Record.size())
1479 return Error(InvalidRecord);
1480
1481 for (unsigned i = 0; i != AsmStrSize; ++i)
1482 AsmStr += (char)Record[2+i];
1483 for (unsigned i = 0; i != ConstStrSize; ++i)
1484 ConstrStr += (char)Record[3+AsmStrSize+i];
1485 PointerType *PTy = cast<PointerType>(CurTy);
1486 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1487 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1488 break;
1489 }
1490 // This version adds support for the asm dialect keywords (e.g.,
1491 // inteldialect).
1492 case bitc::CST_CODE_INLINEASM: {
1493 if (Record.size() < 2)
1494 return Error(InvalidRecord);
1495 std::string AsmStr, ConstrStr;
1496 bool HasSideEffects = Record[0] & 1;
1497 bool IsAlignStack = (Record[0] >> 1) & 1;
1498 unsigned AsmDialect = Record[0] >> 2;
1499 unsigned AsmStrSize = Record[1];
1500 if (2+AsmStrSize >= Record.size())
1501 return Error(InvalidRecord);
1502 unsigned ConstStrSize = Record[2+AsmStrSize];
1503 if (3+AsmStrSize+ConstStrSize > Record.size())
1504 return Error(InvalidRecord);
1505
1506 for (unsigned i = 0; i != AsmStrSize; ++i)
1507 AsmStr += (char)Record[2+i];
1508 for (unsigned i = 0; i != ConstStrSize; ++i)
1509 ConstrStr += (char)Record[3+AsmStrSize+i];
1510 PointerType *PTy = cast<PointerType>(CurTy);
1511 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1512 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1513 InlineAsm::AsmDialect(AsmDialect));
1514 break;
1515 }
1516 case bitc::CST_CODE_BLOCKADDRESS:{
1517 if (Record.size() < 3)
1518 return Error(InvalidRecord);
1519 Type *FnTy = getTypeByID(Record[0]);
1520 if (FnTy == 0)
1521 return Error(InvalidRecord);
1522 Function *Fn =
1523 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1524 if (Fn == 0)
1525 return Error(InvalidRecord);
1526
1527 // If the function is already parsed we can insert the block address right
1528 // away.
1529 if (!Fn->empty()) {
1530 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1531 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1532 if (BBI == BBE)
1533 return Error(InvalidID);
1534 ++BBI;
1535 }
1536 V = BlockAddress::get(Fn, BBI);
1537 } else {
1538 // Otherwise insert a placeholder and remember it so it can be inserted
1539 // when the function is parsed.
1540 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1541 Type::getInt8Ty(Context),
1542 false, GlobalValue::InternalLinkage,
1543 0, "");
1544 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1545 V = FwdRef;
1546 }
1547 break;
1548 }
1549 }
1550
1551 ValueList.AssignValue(V, NextCstNo);
1552 ++NextCstNo;
1553 }
1554 }
1555
ParseUseLists()1556 error_code BitcodeReader::ParseUseLists() {
1557 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1558 return Error(InvalidRecord);
1559
1560 SmallVector<uint64_t, 64> Record;
1561
1562 // Read all the records.
1563 while (1) {
1564 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1565
1566 switch (Entry.Kind) {
1567 case BitstreamEntry::SubBlock: // Handled for us already.
1568 case BitstreamEntry::Error:
1569 return Error(MalformedBlock);
1570 case BitstreamEntry::EndBlock:
1571 return error_code::success();
1572 case BitstreamEntry::Record:
1573 // The interesting case.
1574 break;
1575 }
1576
1577 // Read a use list record.
1578 Record.clear();
1579 switch (Stream.readRecord(Entry.ID, Record)) {
1580 default: // Default behavior: unknown type.
1581 break;
1582 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1583 unsigned RecordLength = Record.size();
1584 if (RecordLength < 1)
1585 return Error(InvalidRecord);
1586 UseListRecords.push_back(Record);
1587 break;
1588 }
1589 }
1590 }
1591 }
1592
1593 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1594 /// remember where it is and then skip it. This lets us lazily deserialize the
1595 /// functions.
RememberAndSkipFunctionBody()1596 error_code BitcodeReader::RememberAndSkipFunctionBody() {
1597 // Get the function we are talking about.
1598 if (FunctionsWithBodies.empty())
1599 return Error(InsufficientFunctionProtos);
1600
1601 Function *Fn = FunctionsWithBodies.back();
1602 FunctionsWithBodies.pop_back();
1603
1604 // Save the current stream state.
1605 uint64_t CurBit = Stream.GetCurrentBitNo();
1606 DeferredFunctionInfo[Fn] = CurBit;
1607
1608 // Skip over the function block for now.
1609 if (Stream.SkipBlock())
1610 return Error(InvalidRecord);
1611 return error_code::success();
1612 }
1613
GlobalCleanup()1614 error_code BitcodeReader::GlobalCleanup() {
1615 // Patch the initializers for globals and aliases up.
1616 ResolveGlobalAndAliasInits();
1617 if (!GlobalInits.empty() || !AliasInits.empty())
1618 return Error(MalformedGlobalInitializerSet);
1619
1620 // Look for intrinsic functions which need to be upgraded at some point
1621 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1622 FI != FE; ++FI) {
1623 Function *NewFn;
1624 if (UpgradeIntrinsicFunction(FI, NewFn))
1625 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1626 }
1627
1628 // Look for global variables which need to be renamed.
1629 for (Module::global_iterator
1630 GI = TheModule->global_begin(), GE = TheModule->global_end();
1631 GI != GE; ++GI)
1632 UpgradeGlobalVariable(GI);
1633 // Force deallocation of memory for these vectors to favor the client that
1634 // want lazy deserialization.
1635 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1636 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1637 return error_code::success();
1638 }
1639
ParseModule(bool Resume)1640 error_code BitcodeReader::ParseModule(bool Resume) {
1641 if (Resume)
1642 Stream.JumpToBit(NextUnreadBit);
1643 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1644 return Error(InvalidRecord);
1645
1646 SmallVector<uint64_t, 64> Record;
1647 std::vector<std::string> SectionTable;
1648 std::vector<std::string> GCTable;
1649
1650 // Read all the records for this module.
1651 while (1) {
1652 BitstreamEntry Entry = Stream.advance();
1653
1654 switch (Entry.Kind) {
1655 case BitstreamEntry::Error:
1656 return Error(MalformedBlock);
1657 case BitstreamEntry::EndBlock:
1658 return GlobalCleanup();
1659
1660 case BitstreamEntry::SubBlock:
1661 switch (Entry.ID) {
1662 default: // Skip unknown content.
1663 if (Stream.SkipBlock())
1664 return Error(InvalidRecord);
1665 break;
1666 case bitc::BLOCKINFO_BLOCK_ID:
1667 if (Stream.ReadBlockInfoBlock())
1668 return Error(MalformedBlock);
1669 break;
1670 case bitc::PARAMATTR_BLOCK_ID:
1671 if (error_code EC = ParseAttributeBlock())
1672 return EC;
1673 break;
1674 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1675 if (error_code EC = ParseAttributeGroupBlock())
1676 return EC;
1677 break;
1678 case bitc::TYPE_BLOCK_ID_NEW:
1679 if (error_code EC = ParseTypeTable())
1680 return EC;
1681 break;
1682 case bitc::VALUE_SYMTAB_BLOCK_ID:
1683 if (error_code EC = ParseValueSymbolTable())
1684 return EC;
1685 SeenValueSymbolTable = true;
1686 break;
1687 case bitc::CONSTANTS_BLOCK_ID:
1688 if (error_code EC = ParseConstants())
1689 return EC;
1690 if (error_code EC = ResolveGlobalAndAliasInits())
1691 return EC;
1692 break;
1693 case bitc::METADATA_BLOCK_ID:
1694 if (error_code EC = ParseMetadata())
1695 return EC;
1696 break;
1697 case bitc::FUNCTION_BLOCK_ID:
1698 // If this is the first function body we've seen, reverse the
1699 // FunctionsWithBodies list.
1700 if (!SeenFirstFunctionBody) {
1701 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1702 if (error_code EC = GlobalCleanup())
1703 return EC;
1704 SeenFirstFunctionBody = true;
1705 }
1706
1707 if (error_code EC = RememberAndSkipFunctionBody())
1708 return EC;
1709 // For streaming bitcode, suspend parsing when we reach the function
1710 // bodies. Subsequent materialization calls will resume it when
1711 // necessary. For streaming, the function bodies must be at the end of
1712 // the bitcode. If the bitcode file is old, the symbol table will be
1713 // at the end instead and will not have been seen yet. In this case,
1714 // just finish the parse now.
1715 if (LazyStreamer && SeenValueSymbolTable) {
1716 NextUnreadBit = Stream.GetCurrentBitNo();
1717 return error_code::success();
1718 }
1719 break;
1720 case bitc::USELIST_BLOCK_ID:
1721 if (error_code EC = ParseUseLists())
1722 return EC;
1723 break;
1724 }
1725 continue;
1726
1727 case BitstreamEntry::Record:
1728 // The interesting case.
1729 break;
1730 }
1731
1732
1733 // Read a record.
1734 switch (Stream.readRecord(Entry.ID, Record)) {
1735 default: break; // Default behavior, ignore unknown content.
1736 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1737 if (Record.size() < 1)
1738 return Error(InvalidRecord);
1739 // Only version #0 and #1 are supported so far.
1740 unsigned module_version = Record[0];
1741 switch (module_version) {
1742 default:
1743 return Error(InvalidValue);
1744 case 0:
1745 UseRelativeIDs = false;
1746 break;
1747 case 1:
1748 UseRelativeIDs = true;
1749 break;
1750 }
1751 break;
1752 }
1753 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1754 std::string S;
1755 if (ConvertToString(Record, 0, S))
1756 return Error(InvalidRecord);
1757 TheModule->setTargetTriple(S);
1758 break;
1759 }
1760 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1761 std::string S;
1762 if (ConvertToString(Record, 0, S))
1763 return Error(InvalidRecord);
1764 TheModule->setDataLayout(S);
1765 break;
1766 }
1767 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1768 std::string S;
1769 if (ConvertToString(Record, 0, S))
1770 return Error(InvalidRecord);
1771 TheModule->setModuleInlineAsm(S);
1772 break;
1773 }
1774 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1775 // FIXME: Remove in 4.0.
1776 std::string S;
1777 if (ConvertToString(Record, 0, S))
1778 return Error(InvalidRecord);
1779 // Ignore value.
1780 break;
1781 }
1782 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1783 std::string S;
1784 if (ConvertToString(Record, 0, S))
1785 return Error(InvalidRecord);
1786 SectionTable.push_back(S);
1787 break;
1788 }
1789 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1790 std::string S;
1791 if (ConvertToString(Record, 0, S))
1792 return Error(InvalidRecord);
1793 GCTable.push_back(S);
1794 break;
1795 }
1796 // GLOBALVAR: [pointer type, isconst, initid,
1797 // linkage, alignment, section, visibility, threadlocal,
1798 // unnamed_addr]
1799 case bitc::MODULE_CODE_GLOBALVAR: {
1800 if (Record.size() < 6)
1801 return Error(InvalidRecord);
1802 Type *Ty = getTypeByID(Record[0]);
1803 if (!Ty)
1804 return Error(InvalidRecord);
1805 if (!Ty->isPointerTy())
1806 return Error(InvalidTypeForValue);
1807 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1808 Ty = cast<PointerType>(Ty)->getElementType();
1809
1810 bool isConstant = Record[1];
1811 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1812 unsigned Alignment = (1 << Record[4]) >> 1;
1813 std::string Section;
1814 if (Record[5]) {
1815 if (Record[5]-1 >= SectionTable.size())
1816 return Error(InvalidID);
1817 Section = SectionTable[Record[5]-1];
1818 }
1819 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1820 if (Record.size() > 6)
1821 Visibility = GetDecodedVisibility(Record[6]);
1822
1823 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1824 if (Record.size() > 7)
1825 TLM = GetDecodedThreadLocalMode(Record[7]);
1826
1827 bool UnnamedAddr = false;
1828 if (Record.size() > 8)
1829 UnnamedAddr = Record[8];
1830
1831 bool ExternallyInitialized = false;
1832 if (Record.size() > 9)
1833 ExternallyInitialized = Record[9];
1834
1835 GlobalVariable *NewGV =
1836 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1837 TLM, AddressSpace, ExternallyInitialized);
1838 NewGV->setAlignment(Alignment);
1839 if (!Section.empty())
1840 NewGV->setSection(Section);
1841 NewGV->setVisibility(Visibility);
1842 NewGV->setUnnamedAddr(UnnamedAddr);
1843
1844 ValueList.push_back(NewGV);
1845
1846 // Remember which value to use for the global initializer.
1847 if (unsigned InitID = Record[2])
1848 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1849 break;
1850 }
1851 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1852 // alignment, section, visibility, gc, unnamed_addr]
1853 case bitc::MODULE_CODE_FUNCTION: {
1854 if (Record.size() < 8)
1855 return Error(InvalidRecord);
1856 Type *Ty = getTypeByID(Record[0]);
1857 if (!Ty)
1858 return Error(InvalidRecord);
1859 if (!Ty->isPointerTy())
1860 return Error(InvalidTypeForValue);
1861 FunctionType *FTy =
1862 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1863 if (!FTy)
1864 return Error(InvalidTypeForValue);
1865
1866 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1867 "", TheModule);
1868
1869 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1870 bool isProto = Record[2];
1871 Func->setLinkage(GetDecodedLinkage(Record[3]));
1872 Func->setAttributes(getAttributes(Record[4]));
1873
1874 Func->setAlignment((1 << Record[5]) >> 1);
1875 if (Record[6]) {
1876 if (Record[6]-1 >= SectionTable.size())
1877 return Error(InvalidID);
1878 Func->setSection(SectionTable[Record[6]-1]);
1879 }
1880 Func->setVisibility(GetDecodedVisibility(Record[7]));
1881 if (Record.size() > 8 && Record[8]) {
1882 if (Record[8]-1 > GCTable.size())
1883 return Error(InvalidID);
1884 Func->setGC(GCTable[Record[8]-1].c_str());
1885 }
1886 bool UnnamedAddr = false;
1887 if (Record.size() > 9)
1888 UnnamedAddr = Record[9];
1889 Func->setUnnamedAddr(UnnamedAddr);
1890 if (Record.size() > 10 && Record[10] != 0)
1891 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1892 ValueList.push_back(Func);
1893
1894 // If this is a function with a body, remember the prototype we are
1895 // creating now, so that we can match up the body with them later.
1896 if (!isProto) {
1897 FunctionsWithBodies.push_back(Func);
1898 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1899 }
1900 break;
1901 }
1902 // ALIAS: [alias type, aliasee val#, linkage]
1903 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1904 case bitc::MODULE_CODE_ALIAS: {
1905 if (Record.size() < 3)
1906 return Error(InvalidRecord);
1907 Type *Ty = getTypeByID(Record[0]);
1908 if (!Ty)
1909 return Error(InvalidRecord);
1910 if (!Ty->isPointerTy())
1911 return Error(InvalidTypeForValue);
1912
1913 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1914 "", 0, TheModule);
1915 // Old bitcode files didn't have visibility field.
1916 if (Record.size() > 3)
1917 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1918 ValueList.push_back(NewGA);
1919 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1920 break;
1921 }
1922 /// MODULE_CODE_PURGEVALS: [numvals]
1923 case bitc::MODULE_CODE_PURGEVALS:
1924 // Trim down the value list to the specified size.
1925 if (Record.size() < 1 || Record[0] > ValueList.size())
1926 return Error(InvalidRecord);
1927 ValueList.shrinkTo(Record[0]);
1928 break;
1929 }
1930 Record.clear();
1931 }
1932 }
1933
ParseBitcodeInto(Module * M)1934 error_code BitcodeReader::ParseBitcodeInto(Module *M) {
1935 TheModule = 0;
1936
1937 if (error_code EC = InitStream())
1938 return EC;
1939
1940 // Sniff for the signature.
1941 if (Stream.Read(8) != 'B' ||
1942 Stream.Read(8) != 'C' ||
1943 Stream.Read(4) != 0x0 ||
1944 Stream.Read(4) != 0xC ||
1945 Stream.Read(4) != 0xE ||
1946 Stream.Read(4) != 0xD)
1947 return Error(InvalidBitcodeSignature);
1948
1949 // We expect a number of well-defined blocks, though we don't necessarily
1950 // need to understand them all.
1951 while (1) {
1952 if (Stream.AtEndOfStream())
1953 return error_code::success();
1954
1955 BitstreamEntry Entry =
1956 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1957
1958 switch (Entry.Kind) {
1959 case BitstreamEntry::Error:
1960 return Error(MalformedBlock);
1961 case BitstreamEntry::EndBlock:
1962 return error_code::success();
1963
1964 case BitstreamEntry::SubBlock:
1965 switch (Entry.ID) {
1966 case bitc::BLOCKINFO_BLOCK_ID:
1967 if (Stream.ReadBlockInfoBlock())
1968 return Error(MalformedBlock);
1969 break;
1970 case bitc::MODULE_BLOCK_ID:
1971 // Reject multiple MODULE_BLOCK's in a single bitstream.
1972 if (TheModule)
1973 return Error(InvalidMultipleBlocks);
1974 TheModule = M;
1975 if (error_code EC = ParseModule(false))
1976 return EC;
1977 if (LazyStreamer)
1978 return error_code::success();
1979 break;
1980 default:
1981 if (Stream.SkipBlock())
1982 return Error(InvalidRecord);
1983 break;
1984 }
1985 continue;
1986 case BitstreamEntry::Record:
1987 // There should be no records in the top-level of blocks.
1988
1989 // The ranlib in Xcode 4 will align archive members by appending newlines
1990 // to the end of them. If this file size is a multiple of 4 but not 8, we
1991 // have to read and ignore these final 4 bytes :-(
1992 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1993 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1994 Stream.AtEndOfStream())
1995 return error_code::success();
1996
1997 return Error(InvalidRecord);
1998 }
1999 }
2000 }
2001
ParseModuleTriple(std::string & Triple)2002 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) {
2003 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2004 return Error(InvalidRecord);
2005
2006 SmallVector<uint64_t, 64> Record;
2007
2008 // Read all the records for this module.
2009 while (1) {
2010 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2011
2012 switch (Entry.Kind) {
2013 case BitstreamEntry::SubBlock: // Handled for us already.
2014 case BitstreamEntry::Error:
2015 return Error(MalformedBlock);
2016 case BitstreamEntry::EndBlock:
2017 return error_code::success();
2018 case BitstreamEntry::Record:
2019 // The interesting case.
2020 break;
2021 }
2022
2023 // Read a record.
2024 switch (Stream.readRecord(Entry.ID, Record)) {
2025 default: break; // Default behavior, ignore unknown content.
2026 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2027 std::string S;
2028 if (ConvertToString(Record, 0, S))
2029 return Error(InvalidRecord);
2030 Triple = S;
2031 break;
2032 }
2033 }
2034 Record.clear();
2035 }
2036 }
2037
ParseTriple(std::string & Triple)2038 error_code BitcodeReader::ParseTriple(std::string &Triple) {
2039 if (error_code EC = InitStream())
2040 return EC;
2041
2042 // Sniff for the signature.
2043 if (Stream.Read(8) != 'B' ||
2044 Stream.Read(8) != 'C' ||
2045 Stream.Read(4) != 0x0 ||
2046 Stream.Read(4) != 0xC ||
2047 Stream.Read(4) != 0xE ||
2048 Stream.Read(4) != 0xD)
2049 return Error(InvalidBitcodeSignature);
2050
2051 // We expect a number of well-defined blocks, though we don't necessarily
2052 // need to understand them all.
2053 while (1) {
2054 BitstreamEntry Entry = Stream.advance();
2055
2056 switch (Entry.Kind) {
2057 case BitstreamEntry::Error:
2058 return Error(MalformedBlock);
2059 case BitstreamEntry::EndBlock:
2060 return error_code::success();
2061
2062 case BitstreamEntry::SubBlock:
2063 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2064 return ParseModuleTriple(Triple);
2065
2066 // Ignore other sub-blocks.
2067 if (Stream.SkipBlock())
2068 return Error(MalformedBlock);
2069 continue;
2070
2071 case BitstreamEntry::Record:
2072 Stream.skipRecord(Entry.ID);
2073 continue;
2074 }
2075 }
2076 }
2077
2078 /// ParseMetadataAttachment - Parse metadata attachments.
ParseMetadataAttachment()2079 error_code BitcodeReader::ParseMetadataAttachment() {
2080 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2081 return Error(InvalidRecord);
2082
2083 SmallVector<uint64_t, 64> Record;
2084 while (1) {
2085 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2086
2087 switch (Entry.Kind) {
2088 case BitstreamEntry::SubBlock: // Handled for us already.
2089 case BitstreamEntry::Error:
2090 return Error(MalformedBlock);
2091 case BitstreamEntry::EndBlock:
2092 return error_code::success();
2093 case BitstreamEntry::Record:
2094 // The interesting case.
2095 break;
2096 }
2097
2098 // Read a metadata attachment record.
2099 Record.clear();
2100 switch (Stream.readRecord(Entry.ID, Record)) {
2101 default: // Default behavior: ignore.
2102 break;
2103 case bitc::METADATA_ATTACHMENT: {
2104 unsigned RecordLength = Record.size();
2105 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2106 return Error(InvalidRecord);
2107 Instruction *Inst = InstructionList[Record[0]];
2108 for (unsigned i = 1; i != RecordLength; i = i+2) {
2109 unsigned Kind = Record[i];
2110 DenseMap<unsigned, unsigned>::iterator I =
2111 MDKindMap.find(Kind);
2112 if (I == MDKindMap.end())
2113 return Error(InvalidID);
2114 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2115 Inst->setMetadata(I->second, cast<MDNode>(Node));
2116 if (I->second == LLVMContext::MD_tbaa)
2117 InstsWithTBAATag.push_back(Inst);
2118 }
2119 break;
2120 }
2121 }
2122 }
2123 }
2124
2125 /// ParseFunctionBody - Lazily parse the specified function body block.
ParseFunctionBody(Function * F)2126 error_code BitcodeReader::ParseFunctionBody(Function *F) {
2127 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2128 return Error(InvalidRecord);
2129
2130 InstructionList.clear();
2131 unsigned ModuleValueListSize = ValueList.size();
2132 unsigned ModuleMDValueListSize = MDValueList.size();
2133
2134 // Add all the function arguments to the value table.
2135 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2136 ValueList.push_back(I);
2137
2138 unsigned NextValueNo = ValueList.size();
2139 BasicBlock *CurBB = 0;
2140 unsigned CurBBNo = 0;
2141
2142 DebugLoc LastLoc;
2143
2144 // Read all the records.
2145 SmallVector<uint64_t, 64> Record;
2146 while (1) {
2147 BitstreamEntry Entry = Stream.advance();
2148
2149 switch (Entry.Kind) {
2150 case BitstreamEntry::Error:
2151 return Error(MalformedBlock);
2152 case BitstreamEntry::EndBlock:
2153 goto OutOfRecordLoop;
2154
2155 case BitstreamEntry::SubBlock:
2156 switch (Entry.ID) {
2157 default: // Skip unknown content.
2158 if (Stream.SkipBlock())
2159 return Error(InvalidRecord);
2160 break;
2161 case bitc::CONSTANTS_BLOCK_ID:
2162 if (error_code EC = ParseConstants())
2163 return EC;
2164 NextValueNo = ValueList.size();
2165 break;
2166 case bitc::VALUE_SYMTAB_BLOCK_ID:
2167 if (error_code EC = ParseValueSymbolTable())
2168 return EC;
2169 break;
2170 case bitc::METADATA_ATTACHMENT_ID:
2171 if (error_code EC = ParseMetadataAttachment())
2172 return EC;
2173 break;
2174 case bitc::METADATA_BLOCK_ID:
2175 if (error_code EC = ParseMetadata())
2176 return EC;
2177 break;
2178 }
2179 continue;
2180
2181 case BitstreamEntry::Record:
2182 // The interesting case.
2183 break;
2184 }
2185
2186 // Read a record.
2187 Record.clear();
2188 Instruction *I = 0;
2189 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2190 switch (BitCode) {
2191 default: // Default behavior: reject
2192 return Error(InvalidValue);
2193 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2194 if (Record.size() < 1 || Record[0] == 0)
2195 return Error(InvalidRecord);
2196 // Create all the basic blocks for the function.
2197 FunctionBBs.resize(Record[0]);
2198 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2199 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2200 CurBB = FunctionBBs[0];
2201 continue;
2202
2203 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2204 // This record indicates that the last instruction is at the same
2205 // location as the previous instruction with a location.
2206 I = 0;
2207
2208 // Get the last instruction emitted.
2209 if (CurBB && !CurBB->empty())
2210 I = &CurBB->back();
2211 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2212 !FunctionBBs[CurBBNo-1]->empty())
2213 I = &FunctionBBs[CurBBNo-1]->back();
2214
2215 if (I == 0)
2216 return Error(InvalidRecord);
2217 I->setDebugLoc(LastLoc);
2218 I = 0;
2219 continue;
2220
2221 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2222 I = 0; // Get the last instruction emitted.
2223 if (CurBB && !CurBB->empty())
2224 I = &CurBB->back();
2225 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2226 !FunctionBBs[CurBBNo-1]->empty())
2227 I = &FunctionBBs[CurBBNo-1]->back();
2228 if (I == 0 || Record.size() < 4)
2229 return Error(InvalidRecord);
2230
2231 unsigned Line = Record[0], Col = Record[1];
2232 unsigned ScopeID = Record[2], IAID = Record[3];
2233
2234 MDNode *Scope = 0, *IA = 0;
2235 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2236 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2237 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2238 I->setDebugLoc(LastLoc);
2239 I = 0;
2240 continue;
2241 }
2242
2243 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2244 unsigned OpNum = 0;
2245 Value *LHS, *RHS;
2246 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2247 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2248 OpNum+1 > Record.size())
2249 return Error(InvalidRecord);
2250
2251 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2252 if (Opc == -1)
2253 return Error(InvalidRecord);
2254 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2255 InstructionList.push_back(I);
2256 if (OpNum < Record.size()) {
2257 if (Opc == Instruction::Add ||
2258 Opc == Instruction::Sub ||
2259 Opc == Instruction::Mul ||
2260 Opc == Instruction::Shl) {
2261 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2262 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2263 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2264 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2265 } else if (Opc == Instruction::SDiv ||
2266 Opc == Instruction::UDiv ||
2267 Opc == Instruction::LShr ||
2268 Opc == Instruction::AShr) {
2269 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2270 cast<BinaryOperator>(I)->setIsExact(true);
2271 } else if (isa<FPMathOperator>(I)) {
2272 FastMathFlags FMF;
2273 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2274 FMF.setUnsafeAlgebra();
2275 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2276 FMF.setNoNaNs();
2277 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2278 FMF.setNoInfs();
2279 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2280 FMF.setNoSignedZeros();
2281 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2282 FMF.setAllowReciprocal();
2283 if (FMF.any())
2284 I->setFastMathFlags(FMF);
2285 }
2286
2287 }
2288 break;
2289 }
2290 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2291 unsigned OpNum = 0;
2292 Value *Op;
2293 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2294 OpNum+2 != Record.size())
2295 return Error(InvalidRecord);
2296
2297 Type *ResTy = getTypeByID(Record[OpNum]);
2298 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2299 if (Opc == -1 || ResTy == 0)
2300 return Error(InvalidRecord);
2301 Instruction *Temp = 0;
2302 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2303 if (Temp) {
2304 InstructionList.push_back(Temp);
2305 CurBB->getInstList().push_back(Temp);
2306 }
2307 } else {
2308 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2309 }
2310 InstructionList.push_back(I);
2311 break;
2312 }
2313 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2314 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2315 unsigned OpNum = 0;
2316 Value *BasePtr;
2317 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2318 return Error(InvalidRecord);
2319
2320 SmallVector<Value*, 16> GEPIdx;
2321 while (OpNum != Record.size()) {
2322 Value *Op;
2323 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2324 return Error(InvalidRecord);
2325 GEPIdx.push_back(Op);
2326 }
2327
2328 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2329 InstructionList.push_back(I);
2330 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2331 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2332 break;
2333 }
2334
2335 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2336 // EXTRACTVAL: [opty, opval, n x indices]
2337 unsigned OpNum = 0;
2338 Value *Agg;
2339 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2340 return Error(InvalidRecord);
2341
2342 SmallVector<unsigned, 4> EXTRACTVALIdx;
2343 for (unsigned RecSize = Record.size();
2344 OpNum != RecSize; ++OpNum) {
2345 uint64_t Index = Record[OpNum];
2346 if ((unsigned)Index != Index)
2347 return Error(InvalidValue);
2348 EXTRACTVALIdx.push_back((unsigned)Index);
2349 }
2350
2351 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2352 InstructionList.push_back(I);
2353 break;
2354 }
2355
2356 case bitc::FUNC_CODE_INST_INSERTVAL: {
2357 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2358 unsigned OpNum = 0;
2359 Value *Agg;
2360 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2361 return Error(InvalidRecord);
2362 Value *Val;
2363 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2364 return Error(InvalidRecord);
2365
2366 SmallVector<unsigned, 4> INSERTVALIdx;
2367 for (unsigned RecSize = Record.size();
2368 OpNum != RecSize; ++OpNum) {
2369 uint64_t Index = Record[OpNum];
2370 if ((unsigned)Index != Index)
2371 return Error(InvalidValue);
2372 INSERTVALIdx.push_back((unsigned)Index);
2373 }
2374
2375 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2376 InstructionList.push_back(I);
2377 break;
2378 }
2379
2380 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2381 // obsolete form of select
2382 // handles select i1 ... in old bitcode
2383 unsigned OpNum = 0;
2384 Value *TrueVal, *FalseVal, *Cond;
2385 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2386 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2387 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2388 return Error(InvalidRecord);
2389
2390 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2391 InstructionList.push_back(I);
2392 break;
2393 }
2394
2395 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2396 // new form of select
2397 // handles select i1 or select [N x i1]
2398 unsigned OpNum = 0;
2399 Value *TrueVal, *FalseVal, *Cond;
2400 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2401 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2402 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2403 return Error(InvalidRecord);
2404
2405 // select condition can be either i1 or [N x i1]
2406 if (VectorType* vector_type =
2407 dyn_cast<VectorType>(Cond->getType())) {
2408 // expect <n x i1>
2409 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2410 return Error(InvalidTypeForValue);
2411 } else {
2412 // expect i1
2413 if (Cond->getType() != Type::getInt1Ty(Context))
2414 return Error(InvalidTypeForValue);
2415 }
2416
2417 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2418 InstructionList.push_back(I);
2419 break;
2420 }
2421
2422 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2423 unsigned OpNum = 0;
2424 Value *Vec, *Idx;
2425 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2426 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2427 return Error(InvalidRecord);
2428 I = ExtractElementInst::Create(Vec, Idx);
2429 InstructionList.push_back(I);
2430 break;
2431 }
2432
2433 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2434 unsigned OpNum = 0;
2435 Value *Vec, *Elt, *Idx;
2436 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2437 popValue(Record, OpNum, NextValueNo,
2438 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2439 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2440 return Error(InvalidRecord);
2441 I = InsertElementInst::Create(Vec, Elt, Idx);
2442 InstructionList.push_back(I);
2443 break;
2444 }
2445
2446 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2447 unsigned OpNum = 0;
2448 Value *Vec1, *Vec2, *Mask;
2449 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2450 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2451 return Error(InvalidRecord);
2452
2453 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2454 return Error(InvalidRecord);
2455 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2456 InstructionList.push_back(I);
2457 break;
2458 }
2459
2460 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2461 // Old form of ICmp/FCmp returning bool
2462 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2463 // both legal on vectors but had different behaviour.
2464 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2465 // FCmp/ICmp returning bool or vector of bool
2466
2467 unsigned OpNum = 0;
2468 Value *LHS, *RHS;
2469 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2470 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2471 OpNum+1 != Record.size())
2472 return Error(InvalidRecord);
2473
2474 if (LHS->getType()->isFPOrFPVectorTy())
2475 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2476 else
2477 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2478 InstructionList.push_back(I);
2479 break;
2480 }
2481
2482 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2483 {
2484 unsigned Size = Record.size();
2485 if (Size == 0) {
2486 I = ReturnInst::Create(Context);
2487 InstructionList.push_back(I);
2488 break;
2489 }
2490
2491 unsigned OpNum = 0;
2492 Value *Op = NULL;
2493 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2494 return Error(InvalidRecord);
2495 if (OpNum != Record.size())
2496 return Error(InvalidRecord);
2497
2498 I = ReturnInst::Create(Context, Op);
2499 InstructionList.push_back(I);
2500 break;
2501 }
2502 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2503 if (Record.size() != 1 && Record.size() != 3)
2504 return Error(InvalidRecord);
2505 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2506 if (TrueDest == 0)
2507 return Error(InvalidRecord);
2508
2509 if (Record.size() == 1) {
2510 I = BranchInst::Create(TrueDest);
2511 InstructionList.push_back(I);
2512 }
2513 else {
2514 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2515 Value *Cond = getValue(Record, 2, NextValueNo,
2516 Type::getInt1Ty(Context));
2517 if (FalseDest == 0 || Cond == 0)
2518 return Error(InvalidRecord);
2519 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2520 InstructionList.push_back(I);
2521 }
2522 break;
2523 }
2524 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2525 // Check magic
2526 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2527 // "New" SwitchInst format with case ranges. The changes to write this
2528 // format were reverted but we still recognize bitcode that uses it.
2529 // Hopefully someday we will have support for case ranges and can use
2530 // this format again.
2531
2532 Type *OpTy = getTypeByID(Record[1]);
2533 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2534
2535 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2536 BasicBlock *Default = getBasicBlock(Record[3]);
2537 if (OpTy == 0 || Cond == 0 || Default == 0)
2538 return Error(InvalidRecord);
2539
2540 unsigned NumCases = Record[4];
2541
2542 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2543 InstructionList.push_back(SI);
2544
2545 unsigned CurIdx = 5;
2546 for (unsigned i = 0; i != NumCases; ++i) {
2547 SmallVector<ConstantInt*, 1> CaseVals;
2548 unsigned NumItems = Record[CurIdx++];
2549 for (unsigned ci = 0; ci != NumItems; ++ci) {
2550 bool isSingleNumber = Record[CurIdx++];
2551
2552 APInt Low;
2553 unsigned ActiveWords = 1;
2554 if (ValueBitWidth > 64)
2555 ActiveWords = Record[CurIdx++];
2556 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2557 ValueBitWidth);
2558 CurIdx += ActiveWords;
2559
2560 if (!isSingleNumber) {
2561 ActiveWords = 1;
2562 if (ValueBitWidth > 64)
2563 ActiveWords = Record[CurIdx++];
2564 APInt High =
2565 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2566 ValueBitWidth);
2567 CurIdx += ActiveWords;
2568
2569 // FIXME: It is not clear whether values in the range should be
2570 // compared as signed or unsigned values. The partially
2571 // implemented changes that used this format in the past used
2572 // unsigned comparisons.
2573 for ( ; Low.ule(High); ++Low)
2574 CaseVals.push_back(ConstantInt::get(Context, Low));
2575 } else
2576 CaseVals.push_back(ConstantInt::get(Context, Low));
2577 }
2578 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2579 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2580 cve = CaseVals.end(); cvi != cve; ++cvi)
2581 SI->addCase(*cvi, DestBB);
2582 }
2583 I = SI;
2584 break;
2585 }
2586
2587 // Old SwitchInst format without case ranges.
2588
2589 if (Record.size() < 3 || (Record.size() & 1) == 0)
2590 return Error(InvalidRecord);
2591 Type *OpTy = getTypeByID(Record[0]);
2592 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2593 BasicBlock *Default = getBasicBlock(Record[2]);
2594 if (OpTy == 0 || Cond == 0 || Default == 0)
2595 return Error(InvalidRecord);
2596 unsigned NumCases = (Record.size()-3)/2;
2597 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2598 InstructionList.push_back(SI);
2599 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2600 ConstantInt *CaseVal =
2601 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2602 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2603 if (CaseVal == 0 || DestBB == 0) {
2604 delete SI;
2605 return Error(InvalidRecord);
2606 }
2607 SI->addCase(CaseVal, DestBB);
2608 }
2609 I = SI;
2610 break;
2611 }
2612 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2613 if (Record.size() < 2)
2614 return Error(InvalidRecord);
2615 Type *OpTy = getTypeByID(Record[0]);
2616 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2617 if (OpTy == 0 || Address == 0)
2618 return Error(InvalidRecord);
2619 unsigned NumDests = Record.size()-2;
2620 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2621 InstructionList.push_back(IBI);
2622 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2623 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2624 IBI->addDestination(DestBB);
2625 } else {
2626 delete IBI;
2627 return Error(InvalidRecord);
2628 }
2629 }
2630 I = IBI;
2631 break;
2632 }
2633
2634 case bitc::FUNC_CODE_INST_INVOKE: {
2635 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2636 if (Record.size() < 4)
2637 return Error(InvalidRecord);
2638 AttributeSet PAL = getAttributes(Record[0]);
2639 unsigned CCInfo = Record[1];
2640 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2641 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2642
2643 unsigned OpNum = 4;
2644 Value *Callee;
2645 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2646 return Error(InvalidRecord);
2647
2648 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2649 FunctionType *FTy = !CalleeTy ? 0 :
2650 dyn_cast<FunctionType>(CalleeTy->getElementType());
2651
2652 // Check that the right number of fixed parameters are here.
2653 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2654 Record.size() < OpNum+FTy->getNumParams())
2655 return Error(InvalidRecord);
2656
2657 SmallVector<Value*, 16> Ops;
2658 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2659 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2660 FTy->getParamType(i)));
2661 if (Ops.back() == 0)
2662 return Error(InvalidRecord);
2663 }
2664
2665 if (!FTy->isVarArg()) {
2666 if (Record.size() != OpNum)
2667 return Error(InvalidRecord);
2668 } else {
2669 // Read type/value pairs for varargs params.
2670 while (OpNum != Record.size()) {
2671 Value *Op;
2672 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2673 return Error(InvalidRecord);
2674 Ops.push_back(Op);
2675 }
2676 }
2677
2678 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2679 InstructionList.push_back(I);
2680 cast<InvokeInst>(I)->setCallingConv(
2681 static_cast<CallingConv::ID>(CCInfo));
2682 cast<InvokeInst>(I)->setAttributes(PAL);
2683 break;
2684 }
2685 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2686 unsigned Idx = 0;
2687 Value *Val = 0;
2688 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2689 return Error(InvalidRecord);
2690 I = ResumeInst::Create(Val);
2691 InstructionList.push_back(I);
2692 break;
2693 }
2694 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2695 I = new UnreachableInst(Context);
2696 InstructionList.push_back(I);
2697 break;
2698 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2699 if (Record.size() < 1 || ((Record.size()-1)&1))
2700 return Error(InvalidRecord);
2701 Type *Ty = getTypeByID(Record[0]);
2702 if (!Ty)
2703 return Error(InvalidRecord);
2704
2705 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2706 InstructionList.push_back(PN);
2707
2708 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2709 Value *V;
2710 // With the new function encoding, it is possible that operands have
2711 // negative IDs (for forward references). Use a signed VBR
2712 // representation to keep the encoding small.
2713 if (UseRelativeIDs)
2714 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2715 else
2716 V = getValue(Record, 1+i, NextValueNo, Ty);
2717 BasicBlock *BB = getBasicBlock(Record[2+i]);
2718 if (!V || !BB)
2719 return Error(InvalidRecord);
2720 PN->addIncoming(V, BB);
2721 }
2722 I = PN;
2723 break;
2724 }
2725
2726 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2727 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2728 unsigned Idx = 0;
2729 if (Record.size() < 4)
2730 return Error(InvalidRecord);
2731 Type *Ty = getTypeByID(Record[Idx++]);
2732 if (!Ty)
2733 return Error(InvalidRecord);
2734 Value *PersFn = 0;
2735 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2736 return Error(InvalidRecord);
2737
2738 bool IsCleanup = !!Record[Idx++];
2739 unsigned NumClauses = Record[Idx++];
2740 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2741 LP->setCleanup(IsCleanup);
2742 for (unsigned J = 0; J != NumClauses; ++J) {
2743 LandingPadInst::ClauseType CT =
2744 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2745 Value *Val;
2746
2747 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2748 delete LP;
2749 return Error(InvalidRecord);
2750 }
2751
2752 assert((CT != LandingPadInst::Catch ||
2753 !isa<ArrayType>(Val->getType())) &&
2754 "Catch clause has a invalid type!");
2755 assert((CT != LandingPadInst::Filter ||
2756 isa<ArrayType>(Val->getType())) &&
2757 "Filter clause has invalid type!");
2758 LP->addClause(Val);
2759 }
2760
2761 I = LP;
2762 InstructionList.push_back(I);
2763 break;
2764 }
2765
2766 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2767 if (Record.size() != 4)
2768 return Error(InvalidRecord);
2769 PointerType *Ty =
2770 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2771 Type *OpTy = getTypeByID(Record[1]);
2772 Value *Size = getFnValueByID(Record[2], OpTy);
2773 unsigned Align = Record[3];
2774 if (!Ty || !Size)
2775 return Error(InvalidRecord);
2776 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2777 InstructionList.push_back(I);
2778 break;
2779 }
2780 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2781 unsigned OpNum = 0;
2782 Value *Op;
2783 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2784 OpNum+2 != Record.size())
2785 return Error(InvalidRecord);
2786
2787 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2788 InstructionList.push_back(I);
2789 break;
2790 }
2791 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2792 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2793 unsigned OpNum = 0;
2794 Value *Op;
2795 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2796 OpNum+4 != Record.size())
2797 return Error(InvalidRecord);
2798
2799
2800 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2801 if (Ordering == NotAtomic || Ordering == Release ||
2802 Ordering == AcquireRelease)
2803 return Error(InvalidRecord);
2804 if (Ordering != NotAtomic && Record[OpNum] == 0)
2805 return Error(InvalidRecord);
2806 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2807
2808 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2809 Ordering, SynchScope);
2810 InstructionList.push_back(I);
2811 break;
2812 }
2813 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2814 unsigned OpNum = 0;
2815 Value *Val, *Ptr;
2816 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2817 popValue(Record, OpNum, NextValueNo,
2818 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2819 OpNum+2 != Record.size())
2820 return Error(InvalidRecord);
2821
2822 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2823 InstructionList.push_back(I);
2824 break;
2825 }
2826 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2827 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2828 unsigned OpNum = 0;
2829 Value *Val, *Ptr;
2830 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2831 popValue(Record, OpNum, NextValueNo,
2832 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2833 OpNum+4 != Record.size())
2834 return Error(InvalidRecord);
2835
2836 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2837 if (Ordering == NotAtomic || Ordering == Acquire ||
2838 Ordering == AcquireRelease)
2839 return Error(InvalidRecord);
2840 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2841 if (Ordering != NotAtomic && Record[OpNum] == 0)
2842 return Error(InvalidRecord);
2843
2844 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2845 Ordering, SynchScope);
2846 InstructionList.push_back(I);
2847 break;
2848 }
2849 case bitc::FUNC_CODE_INST_CMPXCHG: {
2850 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2851 unsigned OpNum = 0;
2852 Value *Ptr, *Cmp, *New;
2853 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2854 popValue(Record, OpNum, NextValueNo,
2855 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2856 popValue(Record, OpNum, NextValueNo,
2857 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2858 OpNum+3 != Record.size())
2859 return Error(InvalidRecord);
2860 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2861 if (Ordering == NotAtomic || Ordering == Unordered)
2862 return Error(InvalidRecord);
2863 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2864 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2865 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2866 InstructionList.push_back(I);
2867 break;
2868 }
2869 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2870 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2871 unsigned OpNum = 0;
2872 Value *Ptr, *Val;
2873 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2874 popValue(Record, OpNum, NextValueNo,
2875 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2876 OpNum+4 != Record.size())
2877 return Error(InvalidRecord);
2878 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2879 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2880 Operation > AtomicRMWInst::LAST_BINOP)
2881 return Error(InvalidRecord);
2882 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2883 if (Ordering == NotAtomic || Ordering == Unordered)
2884 return Error(InvalidRecord);
2885 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2886 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2887 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2888 InstructionList.push_back(I);
2889 break;
2890 }
2891 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2892 if (2 != Record.size())
2893 return Error(InvalidRecord);
2894 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2895 if (Ordering == NotAtomic || Ordering == Unordered ||
2896 Ordering == Monotonic)
2897 return Error(InvalidRecord);
2898 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2899 I = new FenceInst(Context, Ordering, SynchScope);
2900 InstructionList.push_back(I);
2901 break;
2902 }
2903 case bitc::FUNC_CODE_INST_CALL: {
2904 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2905 if (Record.size() < 3)
2906 return Error(InvalidRecord);
2907
2908 AttributeSet PAL = getAttributes(Record[0]);
2909 unsigned CCInfo = Record[1];
2910
2911 unsigned OpNum = 2;
2912 Value *Callee;
2913 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2914 return Error(InvalidRecord);
2915
2916 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2917 FunctionType *FTy = 0;
2918 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2919 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2920 return Error(InvalidRecord);
2921
2922 SmallVector<Value*, 16> Args;
2923 // Read the fixed params.
2924 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2925 if (FTy->getParamType(i)->isLabelTy())
2926 Args.push_back(getBasicBlock(Record[OpNum]));
2927 else
2928 Args.push_back(getValue(Record, OpNum, NextValueNo,
2929 FTy->getParamType(i)));
2930 if (Args.back() == 0)
2931 return Error(InvalidRecord);
2932 }
2933
2934 // Read type/value pairs for varargs params.
2935 if (!FTy->isVarArg()) {
2936 if (OpNum != Record.size())
2937 return Error(InvalidRecord);
2938 } else {
2939 while (OpNum != Record.size()) {
2940 Value *Op;
2941 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2942 return Error(InvalidRecord);
2943 Args.push_back(Op);
2944 }
2945 }
2946
2947 I = CallInst::Create(Callee, Args);
2948 InstructionList.push_back(I);
2949 cast<CallInst>(I)->setCallingConv(
2950 static_cast<CallingConv::ID>(CCInfo>>1));
2951 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2952 cast<CallInst>(I)->setAttributes(PAL);
2953 break;
2954 }
2955 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2956 if (Record.size() < 3)
2957 return Error(InvalidRecord);
2958 Type *OpTy = getTypeByID(Record[0]);
2959 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2960 Type *ResTy = getTypeByID(Record[2]);
2961 if (!OpTy || !Op || !ResTy)
2962 return Error(InvalidRecord);
2963 I = new VAArgInst(Op, ResTy);
2964 InstructionList.push_back(I);
2965 break;
2966 }
2967 }
2968
2969 // Add instruction to end of current BB. If there is no current BB, reject
2970 // this file.
2971 if (CurBB == 0) {
2972 delete I;
2973 return Error(InvalidInstructionWithNoBB);
2974 }
2975 CurBB->getInstList().push_back(I);
2976
2977 // If this was a terminator instruction, move to the next block.
2978 if (isa<TerminatorInst>(I)) {
2979 ++CurBBNo;
2980 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2981 }
2982
2983 // Non-void values get registered in the value table for future use.
2984 if (I && !I->getType()->isVoidTy())
2985 ValueList.AssignValue(I, NextValueNo++);
2986 }
2987
2988 OutOfRecordLoop:
2989
2990 // Check the function list for unresolved values.
2991 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2992 if (A->getParent() == 0) {
2993 // We found at least one unresolved value. Nuke them all to avoid leaks.
2994 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2995 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2996 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2997 delete A;
2998 }
2999 }
3000 return Error(NeverResolvedValueFoundInFunction);
3001 }
3002 }
3003
3004 // FIXME: Check for unresolved forward-declared metadata references
3005 // and clean up leaks.
3006
3007 // See if anything took the address of blocks in this function. If so,
3008 // resolve them now.
3009 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3010 BlockAddrFwdRefs.find(F);
3011 if (BAFRI != BlockAddrFwdRefs.end()) {
3012 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3013 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3014 unsigned BlockIdx = RefList[i].first;
3015 if (BlockIdx >= FunctionBBs.size())
3016 return Error(InvalidID);
3017
3018 GlobalVariable *FwdRef = RefList[i].second;
3019 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3020 FwdRef->eraseFromParent();
3021 }
3022
3023 BlockAddrFwdRefs.erase(BAFRI);
3024 }
3025
3026 // Trim the value list down to the size it was before we parsed this function.
3027 ValueList.shrinkTo(ModuleValueListSize);
3028 MDValueList.shrinkTo(ModuleMDValueListSize);
3029 std::vector<BasicBlock*>().swap(FunctionBBs);
3030 return error_code::success();
3031 }
3032
3033 /// Find the function body in the bitcode stream
FindFunctionInStream(Function * F,DenseMap<Function *,uint64_t>::iterator DeferredFunctionInfoIterator)3034 error_code BitcodeReader::FindFunctionInStream(Function *F,
3035 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3036 while (DeferredFunctionInfoIterator->second == 0) {
3037 if (Stream.AtEndOfStream())
3038 return Error(CouldNotFindFunctionInStream);
3039 // ParseModule will parse the next body in the stream and set its
3040 // position in the DeferredFunctionInfo map.
3041 if (error_code EC = ParseModule(true))
3042 return EC;
3043 }
3044 return error_code::success();
3045 }
3046
3047 //===----------------------------------------------------------------------===//
3048 // GVMaterializer implementation
3049 //===----------------------------------------------------------------------===//
3050
3051
isMaterializable(const GlobalValue * GV) const3052 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3053 if (const Function *F = dyn_cast<Function>(GV)) {
3054 return F->isDeclaration() &&
3055 DeferredFunctionInfo.count(const_cast<Function*>(F));
3056 }
3057 return false;
3058 }
3059
Materialize(GlobalValue * GV)3060 error_code BitcodeReader::Materialize(GlobalValue *GV) {
3061 Function *F = dyn_cast<Function>(GV);
3062 // If it's not a function or is already material, ignore the request.
3063 if (!F || !F->isMaterializable())
3064 return error_code::success();
3065
3066 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3067 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3068 // If its position is recorded as 0, its body is somewhere in the stream
3069 // but we haven't seen it yet.
3070 if (DFII->second == 0 && LazyStreamer)
3071 if (error_code EC = FindFunctionInStream(F, DFII))
3072 return EC;
3073
3074 // Move the bit stream to the saved position of the deferred function body.
3075 Stream.JumpToBit(DFII->second);
3076
3077 if (error_code EC = ParseFunctionBody(F))
3078 return EC;
3079
3080 // Upgrade any old intrinsic calls in the function.
3081 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3082 E = UpgradedIntrinsics.end(); I != E; ++I) {
3083 if (I->first != I->second) {
3084 for (Value::use_iterator UI = I->first->use_begin(),
3085 UE = I->first->use_end(); UI != UE; ) {
3086 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3087 UpgradeIntrinsicCall(CI, I->second);
3088 }
3089 }
3090 }
3091
3092 return error_code::success();
3093 }
3094
isDematerializable(const GlobalValue * GV) const3095 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3096 const Function *F = dyn_cast<Function>(GV);
3097 if (!F || F->isDeclaration())
3098 return false;
3099 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3100 }
3101
Dematerialize(GlobalValue * GV)3102 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3103 Function *F = dyn_cast<Function>(GV);
3104 // If this function isn't dematerializable, this is a noop.
3105 if (!F || !isDematerializable(F))
3106 return;
3107
3108 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3109
3110 // Just forget the function body, we can remat it later.
3111 F->deleteBody();
3112 }
3113
3114
MaterializeModule(Module * M)3115 error_code BitcodeReader::MaterializeModule(Module *M) {
3116 assert(M == TheModule &&
3117 "Can only Materialize the Module this BitcodeReader is attached to.");
3118 // Iterate over the module, deserializing any functions that are still on
3119 // disk.
3120 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3121 F != E; ++F) {
3122 if (F->isMaterializable()) {
3123 if (error_code EC = Materialize(F))
3124 return EC;
3125 }
3126 }
3127 // At this point, if there are any function bodies, the current bit is
3128 // pointing to the END_BLOCK record after them. Now make sure the rest
3129 // of the bits in the module have been read.
3130 if (NextUnreadBit)
3131 ParseModule(true);
3132
3133 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3134 // delete the old functions to clean up. We can't do this unless the entire
3135 // module is materialized because there could always be another function body
3136 // with calls to the old function.
3137 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3138 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3139 if (I->first != I->second) {
3140 for (Value::use_iterator UI = I->first->use_begin(),
3141 UE = I->first->use_end(); UI != UE; ) {
3142 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3143 UpgradeIntrinsicCall(CI, I->second);
3144 }
3145 if (!I->first->use_empty())
3146 I->first->replaceAllUsesWith(I->second);
3147 I->first->eraseFromParent();
3148 }
3149 }
3150 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3151
3152 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3153 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3154
3155 UpgradeDebugInfo(*M);
3156 return error_code::success();
3157 }
3158
InitStream()3159 error_code BitcodeReader::InitStream() {
3160 if (LazyStreamer)
3161 return InitLazyStream();
3162 return InitStreamFromBuffer();
3163 }
3164
InitStreamFromBuffer()3165 error_code BitcodeReader::InitStreamFromBuffer() {
3166 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3167 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3168
3169 if (Buffer->getBufferSize() & 3) {
3170 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3171 return Error(InvalidBitcodeSignature);
3172 else
3173 return Error(BitcodeStreamInvalidSize);
3174 }
3175
3176 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3177 // The magic number is 0x0B17C0DE stored in little endian.
3178 if (isBitcodeWrapper(BufPtr, BufEnd))
3179 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3180 return Error(InvalidBitcodeWrapperHeader);
3181
3182 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3183 Stream.init(*StreamFile);
3184
3185 return error_code::success();
3186 }
3187
InitLazyStream()3188 error_code BitcodeReader::InitLazyStream() {
3189 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3190 // see it.
3191 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3192 StreamFile.reset(new BitstreamReader(Bytes));
3193 Stream.init(*StreamFile);
3194
3195 unsigned char buf[16];
3196 if (Bytes->readBytes(0, 16, buf) == -1)
3197 return Error(BitcodeStreamInvalidSize);
3198
3199 if (!isBitcode(buf, buf + 16))
3200 return Error(InvalidBitcodeSignature);
3201
3202 if (isBitcodeWrapper(buf, buf + 4)) {
3203 const unsigned char *bitcodeStart = buf;
3204 const unsigned char *bitcodeEnd = buf + 16;
3205 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3206 Bytes->dropLeadingBytes(bitcodeStart - buf);
3207 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3208 }
3209 return error_code::success();
3210 }
3211
3212 namespace {
3213 class BitcodeErrorCategoryType : public _do_message {
name() const3214 const char *name() const LLVM_OVERRIDE {
3215 return "llvm.bitcode";
3216 }
message(int IE) const3217 std::string message(int IE) const LLVM_OVERRIDE {
3218 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3219 switch (E) {
3220 case BitcodeReader::BitcodeStreamInvalidSize:
3221 return "Bitcode stream length should be >= 16 bytes and a multiple of 4";
3222 case BitcodeReader::ConflictingMETADATA_KINDRecords:
3223 return "Conflicting METADATA_KIND records";
3224 case BitcodeReader::CouldNotFindFunctionInStream:
3225 return "Could not find function in stream";
3226 case BitcodeReader::ExpectedConstant:
3227 return "Expected a constant";
3228 case BitcodeReader::InsufficientFunctionProtos:
3229 return "Insufficient function protos";
3230 case BitcodeReader::InvalidBitcodeSignature:
3231 return "Invalid bitcode signature";
3232 case BitcodeReader::InvalidBitcodeWrapperHeader:
3233 return "Invalid bitcode wrapper header";
3234 case BitcodeReader::InvalidConstantReference:
3235 return "Invalid ronstant reference";
3236 case BitcodeReader::InvalidID:
3237 return "Invalid ID";
3238 case BitcodeReader::InvalidInstructionWithNoBB:
3239 return "Invalid instruction with no BB";
3240 case BitcodeReader::InvalidRecord:
3241 return "Invalid record";
3242 case BitcodeReader::InvalidTypeForValue:
3243 return "Invalid type for value";
3244 case BitcodeReader::InvalidTYPETable:
3245 return "Invalid TYPE table";
3246 case BitcodeReader::InvalidType:
3247 return "Invalid type";
3248 case BitcodeReader::MalformedBlock:
3249 return "Malformed block";
3250 case BitcodeReader::MalformedGlobalInitializerSet:
3251 return "Malformed global initializer set";
3252 case BitcodeReader::InvalidMultipleBlocks:
3253 return "Invalid multiple blocks";
3254 case BitcodeReader::NeverResolvedValueFoundInFunction:
3255 return "Never resolved value found in function";
3256 case BitcodeReader::InvalidValue:
3257 return "Invalid value";
3258 }
3259 llvm_unreachable("Unknown error type!");
3260 }
3261 };
3262 }
3263
BitcodeErrorCategory()3264 const error_category &BitcodeReader::BitcodeErrorCategory() {
3265 static BitcodeErrorCategoryType O;
3266 return O;
3267 }
3268
3269 //===----------------------------------------------------------------------===//
3270 // External interface
3271 //===----------------------------------------------------------------------===//
3272
3273 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3274 ///
getLazyBitcodeModule(MemoryBuffer * Buffer,LLVMContext & Context,std::string * ErrMsg)3275 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3276 LLVMContext& Context,
3277 std::string *ErrMsg) {
3278 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3279 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3280 M->setMaterializer(R);
3281 if (error_code EC = R->ParseBitcodeInto(M)) {
3282 if (ErrMsg)
3283 *ErrMsg = EC.message();
3284
3285 delete M; // Also deletes R.
3286 return 0;
3287 }
3288 // Have the BitcodeReader dtor delete 'Buffer'.
3289 R->setBufferOwned(true);
3290
3291 R->materializeForwardReferencedFunctions();
3292
3293 return M;
3294 }
3295
3296
getStreamedBitcodeModule(const std::string & name,DataStreamer * streamer,LLVMContext & Context,std::string * ErrMsg)3297 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3298 DataStreamer *streamer,
3299 LLVMContext &Context,
3300 std::string *ErrMsg) {
3301 Module *M = new Module(name, Context);
3302 BitcodeReader *R = new BitcodeReader(streamer, Context);
3303 M->setMaterializer(R);
3304 if (error_code EC = R->ParseBitcodeInto(M)) {
3305 if (ErrMsg)
3306 *ErrMsg = EC.message();
3307 delete M; // Also deletes R.
3308 return 0;
3309 }
3310 R->setBufferOwned(false); // no buffer to delete
3311 return M;
3312 }
3313
3314 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3315 /// If an error occurs, return null and fill in *ErrMsg if non-null.
ParseBitcodeFile(MemoryBuffer * Buffer,LLVMContext & Context,std::string * ErrMsg)3316 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3317 std::string *ErrMsg){
3318 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3319 if (!M) return 0;
3320
3321 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3322 // there was an error.
3323 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3324
3325 // Read in the entire module, and destroy the BitcodeReader.
3326 if (M->MaterializeAllPermanently(ErrMsg)) {
3327 delete M;
3328 return 0;
3329 }
3330
3331 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3332 // written. We must defer until the Module has been fully materialized.
3333
3334 return M;
3335 }
3336
getBitcodeTargetTriple(MemoryBuffer * Buffer,LLVMContext & Context,std::string * ErrMsg)3337 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3338 LLVMContext& Context,
3339 std::string *ErrMsg) {
3340 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3341 // Don't let the BitcodeReader dtor delete 'Buffer'.
3342 R->setBufferOwned(false);
3343
3344 std::string Triple("");
3345 if (error_code EC = R->ParseTriple(Triple))
3346 if (ErrMsg)
3347 *ErrMsg = EC.message();
3348
3349 delete R;
3350 return Triple;
3351 }
3352