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