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