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