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