BitcodeWriter.cpp revision 10c6d12a9fd4dab411091f64db4db69670b88850
1//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===// 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// Bitcode writer implementation. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/Bitcode/ReaderWriter.h" 15#include "llvm/Bitcode/BitstreamWriter.h" 16#include "llvm/Bitcode/LLVMBitCodes.h" 17#include "ValueEnumerator.h" 18#include "llvm/Constants.h" 19#include "llvm/DerivedTypes.h" 20#include "llvm/InlineAsm.h" 21#include "llvm/Instructions.h" 22#include "llvm/Module.h" 23#include "llvm/Operator.h" 24#include "llvm/ValueSymbolTable.h" 25#include "llvm/ADT/Triple.h" 26#include "llvm/Support/ErrorHandling.h" 27#include "llvm/Support/MathExtras.h" 28#include "llvm/Support/raw_ostream.h" 29#include "llvm/Support/Program.h" 30#include <cctype> 31#include <map> 32using namespace llvm; 33 34/// These are manifest constants used by the bitcode writer. They do not need to 35/// be kept in sync with the reader, but need to be consistent within this file. 36enum { 37 CurVersion = 0, 38 39 // VALUE_SYMTAB_BLOCK abbrev id's. 40 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 41 VST_ENTRY_7_ABBREV, 42 VST_ENTRY_6_ABBREV, 43 VST_BBENTRY_6_ABBREV, 44 45 // CONSTANTS_BLOCK abbrev id's. 46 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 47 CONSTANTS_INTEGER_ABBREV, 48 CONSTANTS_CE_CAST_Abbrev, 49 CONSTANTS_NULL_Abbrev, 50 51 // FUNCTION_BLOCK abbrev id's. 52 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 53 FUNCTION_INST_BINOP_ABBREV, 54 FUNCTION_INST_BINOP_FLAGS_ABBREV, 55 FUNCTION_INST_CAST_ABBREV, 56 FUNCTION_INST_RET_VOID_ABBREV, 57 FUNCTION_INST_RET_VAL_ABBREV, 58 FUNCTION_INST_UNREACHABLE_ABBREV 59}; 60 61 62static unsigned GetEncodedCastOpcode(unsigned Opcode) { 63 switch (Opcode) { 64 default: llvm_unreachable("Unknown cast instruction!"); 65 case Instruction::Trunc : return bitc::CAST_TRUNC; 66 case Instruction::ZExt : return bitc::CAST_ZEXT; 67 case Instruction::SExt : return bitc::CAST_SEXT; 68 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 69 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 70 case Instruction::UIToFP : return bitc::CAST_UITOFP; 71 case Instruction::SIToFP : return bitc::CAST_SITOFP; 72 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 73 case Instruction::FPExt : return bitc::CAST_FPEXT; 74 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 75 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 76 case Instruction::BitCast : return bitc::CAST_BITCAST; 77 } 78} 79 80static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 81 switch (Opcode) { 82 default: llvm_unreachable("Unknown binary instruction!"); 83 case Instruction::Add: 84 case Instruction::FAdd: return bitc::BINOP_ADD; 85 case Instruction::Sub: 86 case Instruction::FSub: return bitc::BINOP_SUB; 87 case Instruction::Mul: 88 case Instruction::FMul: return bitc::BINOP_MUL; 89 case Instruction::UDiv: return bitc::BINOP_UDIV; 90 case Instruction::FDiv: 91 case Instruction::SDiv: return bitc::BINOP_SDIV; 92 case Instruction::URem: return bitc::BINOP_UREM; 93 case Instruction::FRem: 94 case Instruction::SRem: return bitc::BINOP_SREM; 95 case Instruction::Shl: return bitc::BINOP_SHL; 96 case Instruction::LShr: return bitc::BINOP_LSHR; 97 case Instruction::AShr: return bitc::BINOP_ASHR; 98 case Instruction::And: return bitc::BINOP_AND; 99 case Instruction::Or: return bitc::BINOP_OR; 100 case Instruction::Xor: return bitc::BINOP_XOR; 101 } 102} 103 104static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 105 switch (Op) { 106 default: llvm_unreachable("Unknown RMW operation!"); 107 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 108 case AtomicRMWInst::Add: return bitc::RMW_ADD; 109 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 110 case AtomicRMWInst::And: return bitc::RMW_AND; 111 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 112 case AtomicRMWInst::Or: return bitc::RMW_OR; 113 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 114 case AtomicRMWInst::Max: return bitc::RMW_MAX; 115 case AtomicRMWInst::Min: return bitc::RMW_MIN; 116 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 117 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 118 } 119} 120 121static unsigned GetEncodedOrdering(AtomicOrdering Ordering) { 122 switch (Ordering) { 123 default: llvm_unreachable("Unknown atomic ordering"); 124 case NotAtomic: return bitc::ORDERING_NOTATOMIC; 125 case Unordered: return bitc::ORDERING_UNORDERED; 126 case Monotonic: return bitc::ORDERING_MONOTONIC; 127 case Acquire: return bitc::ORDERING_ACQUIRE; 128 case Release: return bitc::ORDERING_RELEASE; 129 case AcquireRelease: return bitc::ORDERING_ACQREL; 130 case SequentiallyConsistent: return bitc::ORDERING_SEQCST; 131 } 132} 133 134static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) { 135 switch (SynchScope) { 136 default: llvm_unreachable("Unknown synchronization scope"); 137 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD; 138 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD; 139 } 140} 141 142static void WriteStringRecord(unsigned Code, StringRef Str, 143 unsigned AbbrevToUse, BitstreamWriter &Stream) { 144 SmallVector<unsigned, 64> Vals; 145 146 // Code: [strchar x N] 147 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 148 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 149 AbbrevToUse = 0; 150 Vals.push_back(Str[i]); 151 } 152 153 // Emit the finished record. 154 Stream.EmitRecord(Code, Vals, AbbrevToUse); 155} 156 157// Emit information about parameter attributes. 158static void WriteAttributeTable(const ValueEnumerator &VE, 159 BitstreamWriter &Stream) { 160 const std::vector<AttrListPtr> &Attrs = VE.getAttributes(); 161 if (Attrs.empty()) return; 162 163 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 164 165 SmallVector<uint64_t, 64> Record; 166 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 167 const AttrListPtr &A = Attrs[i]; 168 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) { 169 const AttributeWithIndex &PAWI = A.getSlot(i); 170 Record.push_back(PAWI.Index); 171 172 // FIXME: remove in LLVM 3.0 173 // Store the alignment in the bitcode as a 16-bit raw value instead of a 174 // 5-bit log2 encoded value. Shift the bits above the alignment up by 175 // 11 bits. 176 uint64_t FauxAttr = PAWI.Attrs & 0xffff; 177 if (PAWI.Attrs & Attribute::Alignment) 178 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16); 179 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11; 180 181 Record.push_back(FauxAttr); 182 } 183 184 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 185 Record.clear(); 186 } 187 188 Stream.ExitBlock(); 189} 190 191/// WriteTypeTable - Write out the type table for a module. 192static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 193 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 194 195 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 196 SmallVector<uint64_t, 64> TypeVals; 197 198 // Abbrev for TYPE_CODE_POINTER. 199 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 200 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 202 Log2_32_Ceil(VE.getTypes().size()+1))); 203 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 204 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv); 205 206 // Abbrev for TYPE_CODE_FUNCTION. 207 Abbv = new BitCodeAbbrev(); 208 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 210 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0 211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 213 Log2_32_Ceil(VE.getTypes().size()+1))); 214 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); 215 216 // Abbrev for TYPE_CODE_STRUCT_ANON. 217 Abbv = new BitCodeAbbrev(); 218 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 222 Log2_32_Ceil(VE.getTypes().size()+1))); 223 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv); 224 225 // Abbrev for TYPE_CODE_STRUCT_NAME. 226 Abbv = new BitCodeAbbrev(); 227 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 230 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv); 231 232 // Abbrev for TYPE_CODE_STRUCT_NAMED. 233 Abbv = new BitCodeAbbrev(); 234 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 238 Log2_32_Ceil(VE.getTypes().size()+1))); 239 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv); 240 241 242 // Abbrev for TYPE_CODE_ARRAY. 243 Abbv = new BitCodeAbbrev(); 244 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 247 Log2_32_Ceil(VE.getTypes().size()+1))); 248 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); 249 250 // Emit an entry count so the reader can reserve space. 251 TypeVals.push_back(TypeList.size()); 252 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 253 TypeVals.clear(); 254 255 // Loop over all of the types, emitting each in turn. 256 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 257 Type *T = TypeList[i]; 258 int AbbrevToUse = 0; 259 unsigned Code = 0; 260 261 switch (T->getTypeID()) { 262 default: llvm_unreachable("Unknown type!"); 263 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 264 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 265 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 266 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 267 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 268 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 269 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 270 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 271 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 272 case Type::IntegerTyID: 273 // INTEGER: [width] 274 Code = bitc::TYPE_CODE_INTEGER; 275 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 276 break; 277 case Type::PointerTyID: { 278 PointerType *PTy = cast<PointerType>(T); 279 // POINTER: [pointee type, address space] 280 Code = bitc::TYPE_CODE_POINTER; 281 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 282 unsigned AddressSpace = PTy->getAddressSpace(); 283 TypeVals.push_back(AddressSpace); 284 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 285 break; 286 } 287 case Type::FunctionTyID: { 288 FunctionType *FT = cast<FunctionType>(T); 289 // FUNCTION: [isvararg, attrid, retty, paramty x N] 290 Code = bitc::TYPE_CODE_FUNCTION; 291 TypeVals.push_back(FT->isVarArg()); 292 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0 293 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 294 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 295 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 296 AbbrevToUse = FunctionAbbrev; 297 break; 298 } 299 case Type::StructTyID: { 300 StructType *ST = cast<StructType>(T); 301 // STRUCT: [ispacked, eltty x N] 302 TypeVals.push_back(ST->isPacked()); 303 // Output all of the element types. 304 for (StructType::element_iterator I = ST->element_begin(), 305 E = ST->element_end(); I != E; ++I) 306 TypeVals.push_back(VE.getTypeID(*I)); 307 308 if (ST->isAnonymous()) { 309 Code = bitc::TYPE_CODE_STRUCT_ANON; 310 AbbrevToUse = StructAnonAbbrev; 311 } else { 312 if (ST->isOpaque()) { 313 Code = bitc::TYPE_CODE_OPAQUE; 314 } else { 315 Code = bitc::TYPE_CODE_STRUCT_NAMED; 316 AbbrevToUse = StructNamedAbbrev; 317 } 318 319 // Emit the name if it is present. 320 if (!ST->getName().empty()) 321 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 322 StructNameAbbrev, Stream); 323 } 324 break; 325 } 326 case Type::ArrayTyID: { 327 ArrayType *AT = cast<ArrayType>(T); 328 // ARRAY: [numelts, eltty] 329 Code = bitc::TYPE_CODE_ARRAY; 330 TypeVals.push_back(AT->getNumElements()); 331 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 332 AbbrevToUse = ArrayAbbrev; 333 break; 334 } 335 case Type::VectorTyID: { 336 VectorType *VT = cast<VectorType>(T); 337 // VECTOR [numelts, eltty] 338 Code = bitc::TYPE_CODE_VECTOR; 339 TypeVals.push_back(VT->getNumElements()); 340 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 341 break; 342 } 343 } 344 345 // Emit the finished record. 346 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 347 TypeVals.clear(); 348 } 349 350 Stream.ExitBlock(); 351} 352 353static unsigned getEncodedLinkage(const GlobalValue *GV) { 354 switch (GV->getLinkage()) { 355 default: llvm_unreachable("Invalid linkage!"); 356 case GlobalValue::ExternalLinkage: return 0; 357 case GlobalValue::WeakAnyLinkage: return 1; 358 case GlobalValue::AppendingLinkage: return 2; 359 case GlobalValue::InternalLinkage: return 3; 360 case GlobalValue::LinkOnceAnyLinkage: return 4; 361 case GlobalValue::DLLImportLinkage: return 5; 362 case GlobalValue::DLLExportLinkage: return 6; 363 case GlobalValue::ExternalWeakLinkage: return 7; 364 case GlobalValue::CommonLinkage: return 8; 365 case GlobalValue::PrivateLinkage: return 9; 366 case GlobalValue::WeakODRLinkage: return 10; 367 case GlobalValue::LinkOnceODRLinkage: return 11; 368 case GlobalValue::AvailableExternallyLinkage: return 12; 369 case GlobalValue::LinkerPrivateLinkage: return 13; 370 case GlobalValue::LinkerPrivateWeakLinkage: return 14; 371 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15; 372 } 373} 374 375static unsigned getEncodedVisibility(const GlobalValue *GV) { 376 switch (GV->getVisibility()) { 377 default: llvm_unreachable("Invalid visibility!"); 378 case GlobalValue::DefaultVisibility: return 0; 379 case GlobalValue::HiddenVisibility: return 1; 380 case GlobalValue::ProtectedVisibility: return 2; 381 } 382} 383 384// Emit top-level description of module, including target triple, inline asm, 385// descriptors for global variables, and function prototype info. 386static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 387 BitstreamWriter &Stream) { 388 // Emit the list of dependent libraries for the Module. 389 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I) 390 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream); 391 392 // Emit various pieces of data attached to a module. 393 if (!M->getTargetTriple().empty()) 394 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 395 0/*TODO*/, Stream); 396 if (!M->getDataLayout().empty()) 397 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(), 398 0/*TODO*/, Stream); 399 if (!M->getModuleInlineAsm().empty()) 400 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 401 0/*TODO*/, Stream); 402 403 // Emit information about sections and GC, computing how many there are. Also 404 // compute the maximum alignment value. 405 std::map<std::string, unsigned> SectionMap; 406 std::map<std::string, unsigned> GCMap; 407 unsigned MaxAlignment = 0; 408 unsigned MaxGlobalType = 0; 409 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 410 GV != E; ++GV) { 411 MaxAlignment = std::max(MaxAlignment, GV->getAlignment()); 412 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType())); 413 414 if (!GV->hasSection()) continue; 415 // Give section names unique ID's. 416 unsigned &Entry = SectionMap[GV->getSection()]; 417 if (Entry != 0) continue; 418 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(), 419 0/*TODO*/, Stream); 420 Entry = SectionMap.size(); 421 } 422 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 423 MaxAlignment = std::max(MaxAlignment, F->getAlignment()); 424 if (F->hasSection()) { 425 // Give section names unique ID's. 426 unsigned &Entry = SectionMap[F->getSection()]; 427 if (!Entry) { 428 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(), 429 0/*TODO*/, Stream); 430 Entry = SectionMap.size(); 431 } 432 } 433 if (F->hasGC()) { 434 // Same for GC names. 435 unsigned &Entry = GCMap[F->getGC()]; 436 if (!Entry) { 437 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(), 438 0/*TODO*/, Stream); 439 Entry = GCMap.size(); 440 } 441 } 442 } 443 444 // Emit abbrev for globals, now that we know # sections and max alignment. 445 unsigned SimpleGVarAbbrev = 0; 446 if (!M->global_empty()) { 447 // Add an abbrev for common globals with no visibility or thread localness. 448 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 449 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 451 Log2_32_Ceil(MaxGlobalType+1))); 452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant. 453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage. 455 if (MaxAlignment == 0) // Alignment. 456 Abbv->Add(BitCodeAbbrevOp(0)); 457 else { 458 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 460 Log2_32_Ceil(MaxEncAlignment+1))); 461 } 462 if (SectionMap.empty()) // Section. 463 Abbv->Add(BitCodeAbbrevOp(0)); 464 else 465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 466 Log2_32_Ceil(SectionMap.size()+1))); 467 // Don't bother emitting vis + thread local. 468 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 469 } 470 471 // Emit the global variable information. 472 SmallVector<unsigned, 64> Vals; 473 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 474 GV != E; ++GV) { 475 unsigned AbbrevToUse = 0; 476 477 // GLOBALVAR: [type, isconst, initid, 478 // linkage, alignment, section, visibility, threadlocal, 479 // unnamed_addr] 480 Vals.push_back(VE.getTypeID(GV->getType())); 481 Vals.push_back(GV->isConstant()); 482 Vals.push_back(GV->isDeclaration() ? 0 : 483 (VE.getValueID(GV->getInitializer()) + 1)); 484 Vals.push_back(getEncodedLinkage(GV)); 485 Vals.push_back(Log2_32(GV->getAlignment())+1); 486 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0); 487 if (GV->isThreadLocal() || 488 GV->getVisibility() != GlobalValue::DefaultVisibility || 489 GV->hasUnnamedAddr()) { 490 Vals.push_back(getEncodedVisibility(GV)); 491 Vals.push_back(GV->isThreadLocal()); 492 Vals.push_back(GV->hasUnnamedAddr()); 493 } else { 494 AbbrevToUse = SimpleGVarAbbrev; 495 } 496 497 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 498 Vals.clear(); 499 } 500 501 // Emit the function proto information. 502 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 503 // FUNCTION: [type, callingconv, isproto, paramattr, 504 // linkage, alignment, section, visibility, gc, unnamed_addr] 505 Vals.push_back(VE.getTypeID(F->getType())); 506 Vals.push_back(F->getCallingConv()); 507 Vals.push_back(F->isDeclaration()); 508 Vals.push_back(getEncodedLinkage(F)); 509 Vals.push_back(VE.getAttributeID(F->getAttributes())); 510 Vals.push_back(Log2_32(F->getAlignment())+1); 511 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0); 512 Vals.push_back(getEncodedVisibility(F)); 513 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0); 514 Vals.push_back(F->hasUnnamedAddr()); 515 516 unsigned AbbrevToUse = 0; 517 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 518 Vals.clear(); 519 } 520 521 // Emit the alias information. 522 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); 523 AI != E; ++AI) { 524 Vals.push_back(VE.getTypeID(AI->getType())); 525 Vals.push_back(VE.getValueID(AI->getAliasee())); 526 Vals.push_back(getEncodedLinkage(AI)); 527 Vals.push_back(getEncodedVisibility(AI)); 528 unsigned AbbrevToUse = 0; 529 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 530 Vals.clear(); 531 } 532} 533 534static uint64_t GetOptimizationFlags(const Value *V) { 535 uint64_t Flags = 0; 536 537 if (const OverflowingBinaryOperator *OBO = 538 dyn_cast<OverflowingBinaryOperator>(V)) { 539 if (OBO->hasNoSignedWrap()) 540 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 541 if (OBO->hasNoUnsignedWrap()) 542 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 543 } else if (const PossiblyExactOperator *PEO = 544 dyn_cast<PossiblyExactOperator>(V)) { 545 if (PEO->isExact()) 546 Flags |= 1 << bitc::PEO_EXACT; 547 } 548 549 return Flags; 550} 551 552static void WriteMDNode(const MDNode *N, 553 const ValueEnumerator &VE, 554 BitstreamWriter &Stream, 555 SmallVector<uint64_t, 64> &Record) { 556 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 557 if (N->getOperand(i)) { 558 Record.push_back(VE.getTypeID(N->getOperand(i)->getType())); 559 Record.push_back(VE.getValueID(N->getOperand(i))); 560 } else { 561 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext()))); 562 Record.push_back(0); 563 } 564 } 565 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE : 566 bitc::METADATA_NODE; 567 Stream.EmitRecord(MDCode, Record, 0); 568 Record.clear(); 569} 570 571static void WriteModuleMetadata(const Module *M, 572 const ValueEnumerator &VE, 573 BitstreamWriter &Stream) { 574 const ValueEnumerator::ValueList &Vals = VE.getMDValues(); 575 bool StartedMetadataBlock = false; 576 unsigned MDSAbbrev = 0; 577 SmallVector<uint64_t, 64> Record; 578 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 579 580 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) { 581 if (!N->isFunctionLocal() || !N->getFunction()) { 582 if (!StartedMetadataBlock) { 583 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 584 StartedMetadataBlock = true; 585 } 586 WriteMDNode(N, VE, Stream, Record); 587 } 588 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) { 589 if (!StartedMetadataBlock) { 590 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 591 592 // Abbrev for METADATA_STRING. 593 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 594 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING)); 595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 596 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 597 MDSAbbrev = Stream.EmitAbbrev(Abbv); 598 StartedMetadataBlock = true; 599 } 600 601 // Code: [strchar x N] 602 Record.append(MDS->begin(), MDS->end()); 603 604 // Emit the finished record. 605 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev); 606 Record.clear(); 607 } 608 } 609 610 // Write named metadata. 611 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 612 E = M->named_metadata_end(); I != E; ++I) { 613 const NamedMDNode *NMD = I; 614 if (!StartedMetadataBlock) { 615 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 616 StartedMetadataBlock = true; 617 } 618 619 // Write name. 620 StringRef Str = NMD->getName(); 621 for (unsigned i = 0, e = Str.size(); i != e; ++i) 622 Record.push_back(Str[i]); 623 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/); 624 Record.clear(); 625 626 // Write named metadata operands. 627 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) 628 Record.push_back(VE.getValueID(NMD->getOperand(i))); 629 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 630 Record.clear(); 631 } 632 633 if (StartedMetadataBlock) 634 Stream.ExitBlock(); 635} 636 637static void WriteFunctionLocalMetadata(const Function &F, 638 const ValueEnumerator &VE, 639 BitstreamWriter &Stream) { 640 bool StartedMetadataBlock = false; 641 SmallVector<uint64_t, 64> Record; 642 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues(); 643 for (unsigned i = 0, e = Vals.size(); i != e; ++i) 644 if (const MDNode *N = Vals[i]) 645 if (N->isFunctionLocal() && N->getFunction() == &F) { 646 if (!StartedMetadataBlock) { 647 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 648 StartedMetadataBlock = true; 649 } 650 WriteMDNode(N, VE, Stream, Record); 651 } 652 653 if (StartedMetadataBlock) 654 Stream.ExitBlock(); 655} 656 657static void WriteMetadataAttachment(const Function &F, 658 const ValueEnumerator &VE, 659 BitstreamWriter &Stream) { 660 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 661 662 SmallVector<uint64_t, 64> Record; 663 664 // Write metadata attachments 665 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 666 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs; 667 668 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 669 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 670 I != E; ++I) { 671 MDs.clear(); 672 I->getAllMetadataOtherThanDebugLoc(MDs); 673 674 // If no metadata, ignore instruction. 675 if (MDs.empty()) continue; 676 677 Record.push_back(VE.getInstructionID(I)); 678 679 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 680 Record.push_back(MDs[i].first); 681 Record.push_back(VE.getValueID(MDs[i].second)); 682 } 683 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 684 Record.clear(); 685 } 686 687 Stream.ExitBlock(); 688} 689 690static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { 691 SmallVector<uint64_t, 64> Record; 692 693 // Write metadata kinds 694 // METADATA_KIND - [n x [id, name]] 695 SmallVector<StringRef, 4> Names; 696 M->getMDKindNames(Names); 697 698 if (Names.empty()) return; 699 700 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 701 702 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 703 Record.push_back(MDKindID); 704 StringRef KName = Names[MDKindID]; 705 Record.append(KName.begin(), KName.end()); 706 707 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 708 Record.clear(); 709 } 710 711 Stream.ExitBlock(); 712} 713 714static void WriteConstants(unsigned FirstVal, unsigned LastVal, 715 const ValueEnumerator &VE, 716 BitstreamWriter &Stream, bool isGlobal) { 717 if (FirstVal == LastVal) return; 718 719 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 720 721 unsigned AggregateAbbrev = 0; 722 unsigned String8Abbrev = 0; 723 unsigned CString7Abbrev = 0; 724 unsigned CString6Abbrev = 0; 725 // If this is a constant pool for the module, emit module-specific abbrevs. 726 if (isGlobal) { 727 // Abbrev for CST_CODE_AGGREGATE. 728 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 729 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 732 AggregateAbbrev = Stream.EmitAbbrev(Abbv); 733 734 // Abbrev for CST_CODE_STRING. 735 Abbv = new BitCodeAbbrev(); 736 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 737 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 739 String8Abbrev = Stream.EmitAbbrev(Abbv); 740 // Abbrev for CST_CODE_CSTRING. 741 Abbv = new BitCodeAbbrev(); 742 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 745 CString7Abbrev = Stream.EmitAbbrev(Abbv); 746 // Abbrev for CST_CODE_CSTRING. 747 Abbv = new BitCodeAbbrev(); 748 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 751 CString6Abbrev = Stream.EmitAbbrev(Abbv); 752 } 753 754 SmallVector<uint64_t, 64> Record; 755 756 const ValueEnumerator::ValueList &Vals = VE.getValues(); 757 Type *LastTy = 0; 758 for (unsigned i = FirstVal; i != LastVal; ++i) { 759 const Value *V = Vals[i].first; 760 // If we need to switch types, do so now. 761 if (V->getType() != LastTy) { 762 LastTy = V->getType(); 763 Record.push_back(VE.getTypeID(LastTy)); 764 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 765 CONSTANTS_SETTYPE_ABBREV); 766 Record.clear(); 767 } 768 769 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 770 Record.push_back(unsigned(IA->hasSideEffects()) | 771 unsigned(IA->isAlignStack()) << 1); 772 773 // Add the asm string. 774 const std::string &AsmStr = IA->getAsmString(); 775 Record.push_back(AsmStr.size()); 776 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i) 777 Record.push_back(AsmStr[i]); 778 779 // Add the constraint string. 780 const std::string &ConstraintStr = IA->getConstraintString(); 781 Record.push_back(ConstraintStr.size()); 782 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i) 783 Record.push_back(ConstraintStr[i]); 784 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 785 Record.clear(); 786 continue; 787 } 788 const Constant *C = cast<Constant>(V); 789 unsigned Code = -1U; 790 unsigned AbbrevToUse = 0; 791 if (C->isNullValue()) { 792 Code = bitc::CST_CODE_NULL; 793 } else if (isa<UndefValue>(C)) { 794 Code = bitc::CST_CODE_UNDEF; 795 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 796 if (IV->getBitWidth() <= 64) { 797 uint64_t V = IV->getSExtValue(); 798 if ((int64_t)V >= 0) 799 Record.push_back(V << 1); 800 else 801 Record.push_back((-V << 1) | 1); 802 Code = bitc::CST_CODE_INTEGER; 803 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 804 } else { // Wide integers, > 64 bits in size. 805 // We have an arbitrary precision integer value to write whose 806 // bit width is > 64. However, in canonical unsigned integer 807 // format it is likely that the high bits are going to be zero. 808 // So, we only write the number of active words. 809 unsigned NWords = IV->getValue().getActiveWords(); 810 const uint64_t *RawWords = IV->getValue().getRawData(); 811 for (unsigned i = 0; i != NWords; ++i) { 812 int64_t V = RawWords[i]; 813 if (V >= 0) 814 Record.push_back(V << 1); 815 else 816 Record.push_back((-V << 1) | 1); 817 } 818 Code = bitc::CST_CODE_WIDE_INTEGER; 819 } 820 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 821 Code = bitc::CST_CODE_FLOAT; 822 Type *Ty = CFP->getType(); 823 if (Ty->isFloatTy() || Ty->isDoubleTy()) { 824 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 825 } else if (Ty->isX86_FP80Ty()) { 826 // api needed to prevent premature destruction 827 // bits are not in the same order as a normal i80 APInt, compensate. 828 APInt api = CFP->getValueAPF().bitcastToAPInt(); 829 const uint64_t *p = api.getRawData(); 830 Record.push_back((p[1] << 48) | (p[0] >> 16)); 831 Record.push_back(p[0] & 0xffffLL); 832 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 833 APInt api = CFP->getValueAPF().bitcastToAPInt(); 834 const uint64_t *p = api.getRawData(); 835 Record.push_back(p[0]); 836 Record.push_back(p[1]); 837 } else { 838 assert (0 && "Unknown FP type!"); 839 } 840 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) { 841 const ConstantArray *CA = cast<ConstantArray>(C); 842 // Emit constant strings specially. 843 unsigned NumOps = CA->getNumOperands(); 844 // If this is a null-terminated string, use the denser CSTRING encoding. 845 if (CA->getOperand(NumOps-1)->isNullValue()) { 846 Code = bitc::CST_CODE_CSTRING; 847 --NumOps; // Don't encode the null, which isn't allowed by char6. 848 } else { 849 Code = bitc::CST_CODE_STRING; 850 AbbrevToUse = String8Abbrev; 851 } 852 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 853 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 854 for (unsigned i = 0; i != NumOps; ++i) { 855 unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue(); 856 Record.push_back(V); 857 isCStr7 &= (V & 128) == 0; 858 if (isCStrChar6) 859 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 860 } 861 862 if (isCStrChar6) 863 AbbrevToUse = CString6Abbrev; 864 else if (isCStr7) 865 AbbrevToUse = CString7Abbrev; 866 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) || 867 isa<ConstantVector>(V)) { 868 Code = bitc::CST_CODE_AGGREGATE; 869 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) 870 Record.push_back(VE.getValueID(C->getOperand(i))); 871 AbbrevToUse = AggregateAbbrev; 872 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 873 switch (CE->getOpcode()) { 874 default: 875 if (Instruction::isCast(CE->getOpcode())) { 876 Code = bitc::CST_CODE_CE_CAST; 877 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 878 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 879 Record.push_back(VE.getValueID(C->getOperand(0))); 880 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 881 } else { 882 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 883 Code = bitc::CST_CODE_CE_BINOP; 884 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 885 Record.push_back(VE.getValueID(C->getOperand(0))); 886 Record.push_back(VE.getValueID(C->getOperand(1))); 887 uint64_t Flags = GetOptimizationFlags(CE); 888 if (Flags != 0) 889 Record.push_back(Flags); 890 } 891 break; 892 case Instruction::GetElementPtr: 893 Code = bitc::CST_CODE_CE_GEP; 894 if (cast<GEPOperator>(C)->isInBounds()) 895 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 896 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 897 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 898 Record.push_back(VE.getValueID(C->getOperand(i))); 899 } 900 break; 901 case Instruction::Select: 902 Code = bitc::CST_CODE_CE_SELECT; 903 Record.push_back(VE.getValueID(C->getOperand(0))); 904 Record.push_back(VE.getValueID(C->getOperand(1))); 905 Record.push_back(VE.getValueID(C->getOperand(2))); 906 break; 907 case Instruction::ExtractElement: 908 Code = bitc::CST_CODE_CE_EXTRACTELT; 909 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 910 Record.push_back(VE.getValueID(C->getOperand(0))); 911 Record.push_back(VE.getValueID(C->getOperand(1))); 912 break; 913 case Instruction::InsertElement: 914 Code = bitc::CST_CODE_CE_INSERTELT; 915 Record.push_back(VE.getValueID(C->getOperand(0))); 916 Record.push_back(VE.getValueID(C->getOperand(1))); 917 Record.push_back(VE.getValueID(C->getOperand(2))); 918 break; 919 case Instruction::ShuffleVector: 920 // If the return type and argument types are the same, this is a 921 // standard shufflevector instruction. If the types are different, 922 // then the shuffle is widening or truncating the input vectors, and 923 // the argument type must also be encoded. 924 if (C->getType() == C->getOperand(0)->getType()) { 925 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 926 } else { 927 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 928 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 929 } 930 Record.push_back(VE.getValueID(C->getOperand(0))); 931 Record.push_back(VE.getValueID(C->getOperand(1))); 932 Record.push_back(VE.getValueID(C->getOperand(2))); 933 break; 934 case Instruction::ICmp: 935 case Instruction::FCmp: 936 Code = bitc::CST_CODE_CE_CMP; 937 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 938 Record.push_back(VE.getValueID(C->getOperand(0))); 939 Record.push_back(VE.getValueID(C->getOperand(1))); 940 Record.push_back(CE->getPredicate()); 941 break; 942 } 943 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 944 Code = bitc::CST_CODE_BLOCKADDRESS; 945 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 946 Record.push_back(VE.getValueID(BA->getFunction())); 947 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 948 } else { 949#ifndef NDEBUG 950 C->dump(); 951#endif 952 llvm_unreachable("Unknown constant!"); 953 } 954 Stream.EmitRecord(Code, Record, AbbrevToUse); 955 Record.clear(); 956 } 957 958 Stream.ExitBlock(); 959} 960 961static void WriteModuleConstants(const ValueEnumerator &VE, 962 BitstreamWriter &Stream) { 963 const ValueEnumerator::ValueList &Vals = VE.getValues(); 964 965 // Find the first constant to emit, which is the first non-globalvalue value. 966 // We know globalvalues have been emitted by WriteModuleInfo. 967 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 968 if (!isa<GlobalValue>(Vals[i].first)) { 969 WriteConstants(i, Vals.size(), VE, Stream, true); 970 return; 971 } 972 } 973} 974 975/// PushValueAndType - The file has to encode both the value and type id for 976/// many values, because we need to know what type to create for forward 977/// references. However, most operands are not forward references, so this type 978/// field is not needed. 979/// 980/// This function adds V's value ID to Vals. If the value ID is higher than the 981/// instruction ID, then it is a forward reference, and it also includes the 982/// type ID. 983static bool PushValueAndType(const Value *V, unsigned InstID, 984 SmallVector<unsigned, 64> &Vals, 985 ValueEnumerator &VE) { 986 unsigned ValID = VE.getValueID(V); 987 Vals.push_back(ValID); 988 if (ValID >= InstID) { 989 Vals.push_back(VE.getTypeID(V->getType())); 990 return true; 991 } 992 return false; 993} 994 995/// WriteInstruction - Emit an instruction to the specified stream. 996static void WriteInstruction(const Instruction &I, unsigned InstID, 997 ValueEnumerator &VE, BitstreamWriter &Stream, 998 SmallVector<unsigned, 64> &Vals) { 999 unsigned Code = 0; 1000 unsigned AbbrevToUse = 0; 1001 VE.setInstructionID(&I); 1002 switch (I.getOpcode()) { 1003 default: 1004 if (Instruction::isCast(I.getOpcode())) { 1005 Code = bitc::FUNC_CODE_INST_CAST; 1006 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1007 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 1008 Vals.push_back(VE.getTypeID(I.getType())); 1009 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 1010 } else { 1011 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 1012 Code = bitc::FUNC_CODE_INST_BINOP; 1013 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1014 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 1015 Vals.push_back(VE.getValueID(I.getOperand(1))); 1016 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 1017 uint64_t Flags = GetOptimizationFlags(&I); 1018 if (Flags != 0) { 1019 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 1020 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 1021 Vals.push_back(Flags); 1022 } 1023 } 1024 break; 1025 1026 case Instruction::GetElementPtr: 1027 Code = bitc::FUNC_CODE_INST_GEP; 1028 if (cast<GEPOperator>(&I)->isInBounds()) 1029 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP; 1030 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1031 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1032 break; 1033 case Instruction::ExtractValue: { 1034 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 1035 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1036 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 1037 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 1038 Vals.push_back(*i); 1039 break; 1040 } 1041 case Instruction::InsertValue: { 1042 Code = bitc::FUNC_CODE_INST_INSERTVAL; 1043 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1044 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1045 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 1046 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 1047 Vals.push_back(*i); 1048 break; 1049 } 1050 case Instruction::Select: 1051 Code = bitc::FUNC_CODE_INST_VSELECT; 1052 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1053 Vals.push_back(VE.getValueID(I.getOperand(2))); 1054 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1055 break; 1056 case Instruction::ExtractElement: 1057 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 1058 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1059 Vals.push_back(VE.getValueID(I.getOperand(1))); 1060 break; 1061 case Instruction::InsertElement: 1062 Code = bitc::FUNC_CODE_INST_INSERTELT; 1063 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1064 Vals.push_back(VE.getValueID(I.getOperand(1))); 1065 Vals.push_back(VE.getValueID(I.getOperand(2))); 1066 break; 1067 case Instruction::ShuffleVector: 1068 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 1069 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1070 Vals.push_back(VE.getValueID(I.getOperand(1))); 1071 Vals.push_back(VE.getValueID(I.getOperand(2))); 1072 break; 1073 case Instruction::ICmp: 1074 case Instruction::FCmp: 1075 // compare returning Int1Ty or vector of Int1Ty 1076 Code = bitc::FUNC_CODE_INST_CMP2; 1077 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1078 Vals.push_back(VE.getValueID(I.getOperand(1))); 1079 Vals.push_back(cast<CmpInst>(I).getPredicate()); 1080 break; 1081 1082 case Instruction::Ret: 1083 { 1084 Code = bitc::FUNC_CODE_INST_RET; 1085 unsigned NumOperands = I.getNumOperands(); 1086 if (NumOperands == 0) 1087 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 1088 else if (NumOperands == 1) { 1089 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1090 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 1091 } else { 1092 for (unsigned i = 0, e = NumOperands; i != e; ++i) 1093 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1094 } 1095 } 1096 break; 1097 case Instruction::Br: 1098 { 1099 Code = bitc::FUNC_CODE_INST_BR; 1100 BranchInst &II = cast<BranchInst>(I); 1101 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 1102 if (II.isConditional()) { 1103 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 1104 Vals.push_back(VE.getValueID(II.getCondition())); 1105 } 1106 } 1107 break; 1108 case Instruction::Switch: 1109 Code = bitc::FUNC_CODE_INST_SWITCH; 1110 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1111 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1112 Vals.push_back(VE.getValueID(I.getOperand(i))); 1113 break; 1114 case Instruction::IndirectBr: 1115 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 1116 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1117 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1118 Vals.push_back(VE.getValueID(I.getOperand(i))); 1119 break; 1120 1121 case Instruction::Invoke: { 1122 const InvokeInst *II = cast<InvokeInst>(&I); 1123 const Value *Callee(II->getCalledValue()); 1124 PointerType *PTy = cast<PointerType>(Callee->getType()); 1125 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1126 Code = bitc::FUNC_CODE_INST_INVOKE; 1127 1128 Vals.push_back(VE.getAttributeID(II->getAttributes())); 1129 Vals.push_back(II->getCallingConv()); 1130 Vals.push_back(VE.getValueID(II->getNormalDest())); 1131 Vals.push_back(VE.getValueID(II->getUnwindDest())); 1132 PushValueAndType(Callee, InstID, Vals, VE); 1133 1134 // Emit value #'s for the fixed parameters. 1135 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1136 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param. 1137 1138 // Emit type/value pairs for varargs params. 1139 if (FTy->isVarArg()) { 1140 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 1141 i != e; ++i) 1142 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg 1143 } 1144 break; 1145 } 1146 case Instruction::Unwind: 1147 Code = bitc::FUNC_CODE_INST_UNWIND; 1148 break; 1149 case Instruction::Unreachable: 1150 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 1151 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 1152 break; 1153 1154 case Instruction::PHI: { 1155 const PHINode &PN = cast<PHINode>(I); 1156 Code = bitc::FUNC_CODE_INST_PHI; 1157 Vals.push_back(VE.getTypeID(PN.getType())); 1158 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1159 Vals.push_back(VE.getValueID(PN.getIncomingValue(i))); 1160 Vals.push_back(VE.getValueID(PN.getIncomingBlock(i))); 1161 } 1162 break; 1163 } 1164 1165 case Instruction::Alloca: 1166 Code = bitc::FUNC_CODE_INST_ALLOCA; 1167 Vals.push_back(VE.getTypeID(I.getType())); 1168 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1169 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 1170 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1); 1171 break; 1172 1173 case Instruction::Load: 1174 Code = bitc::FUNC_CODE_INST_LOAD; 1175 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr 1176 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 1177 1178 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 1179 Vals.push_back(cast<LoadInst>(I).isVolatile()); 1180 break; 1181 case Instruction::Store: 1182 Code = bitc::FUNC_CODE_INST_STORE; 1183 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr 1184 Vals.push_back(VE.getValueID(I.getOperand(0))); // val. 1185 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 1186 Vals.push_back(cast<StoreInst>(I).isVolatile()); 1187 break; 1188 case Instruction::AtomicCmpXchg: 1189 Code = bitc::FUNC_CODE_INST_CMPXCHG; 1190 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 1191 Vals.push_back(VE.getValueID(I.getOperand(1))); // cmp. 1192 Vals.push_back(VE.getValueID(I.getOperand(2))); // newval. 1193 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 1194 Vals.push_back(GetEncodedOrdering( 1195 cast<AtomicCmpXchgInst>(I).getOrdering())); 1196 Vals.push_back(GetEncodedSynchScope( 1197 cast<AtomicCmpXchgInst>(I).getSynchScope())); 1198 break; 1199 case Instruction::AtomicRMW: 1200 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 1201 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 1202 Vals.push_back(VE.getValueID(I.getOperand(1))); // val. 1203 Vals.push_back(GetEncodedRMWOperation( 1204 cast<AtomicRMWInst>(I).getOperation())); 1205 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 1206 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 1207 Vals.push_back(GetEncodedSynchScope( 1208 cast<AtomicRMWInst>(I).getSynchScope())); 1209 break; 1210 case Instruction::Fence: 1211 Code = bitc::FUNC_CODE_INST_FENCE; 1212 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering())); 1213 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope())); 1214 break; 1215 case Instruction::Call: { 1216 const CallInst &CI = cast<CallInst>(I); 1217 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType()); 1218 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1219 1220 Code = bitc::FUNC_CODE_INST_CALL; 1221 1222 Vals.push_back(VE.getAttributeID(CI.getAttributes())); 1223 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall())); 1224 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee 1225 1226 // Emit value #'s for the fixed parameters. 1227 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1228 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param. 1229 1230 // Emit type/value pairs for varargs params. 1231 if (FTy->isVarArg()) { 1232 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 1233 i != e; ++i) 1234 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs 1235 } 1236 break; 1237 } 1238 case Instruction::VAArg: 1239 Code = bitc::FUNC_CODE_INST_VAARG; 1240 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 1241 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist. 1242 Vals.push_back(VE.getTypeID(I.getType())); // restype. 1243 break; 1244 } 1245 1246 Stream.EmitRecord(Code, Vals, AbbrevToUse); 1247 Vals.clear(); 1248} 1249 1250// Emit names for globals/functions etc. 1251static void WriteValueSymbolTable(const ValueSymbolTable &VST, 1252 const ValueEnumerator &VE, 1253 BitstreamWriter &Stream) { 1254 if (VST.empty()) return; 1255 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 1256 1257 // FIXME: Set up the abbrev, we know how many values there are! 1258 // FIXME: We know if the type names can use 7-bit ascii. 1259 SmallVector<unsigned, 64> NameVals; 1260 1261 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); 1262 SI != SE; ++SI) { 1263 1264 const ValueName &Name = *SI; 1265 1266 // Figure out the encoding to use for the name. 1267 bool is7Bit = true; 1268 bool isChar6 = true; 1269 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength(); 1270 C != E; ++C) { 1271 if (isChar6) 1272 isChar6 = BitCodeAbbrevOp::isChar6(*C); 1273 if ((unsigned char)*C & 128) { 1274 is7Bit = false; 1275 break; // don't bother scanning the rest. 1276 } 1277 } 1278 1279 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 1280 1281 // VST_ENTRY: [valueid, namechar x N] 1282 // VST_BBENTRY: [bbid, namechar x N] 1283 unsigned Code; 1284 if (isa<BasicBlock>(SI->getValue())) { 1285 Code = bitc::VST_CODE_BBENTRY; 1286 if (isChar6) 1287 AbbrevToUse = VST_BBENTRY_6_ABBREV; 1288 } else { 1289 Code = bitc::VST_CODE_ENTRY; 1290 if (isChar6) 1291 AbbrevToUse = VST_ENTRY_6_ABBREV; 1292 else if (is7Bit) 1293 AbbrevToUse = VST_ENTRY_7_ABBREV; 1294 } 1295 1296 NameVals.push_back(VE.getValueID(SI->getValue())); 1297 for (const char *P = Name.getKeyData(), 1298 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P) 1299 NameVals.push_back((unsigned char)*P); 1300 1301 // Emit the finished record. 1302 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 1303 NameVals.clear(); 1304 } 1305 Stream.ExitBlock(); 1306} 1307 1308/// WriteFunction - Emit a function body to the module stream. 1309static void WriteFunction(const Function &F, ValueEnumerator &VE, 1310 BitstreamWriter &Stream) { 1311 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 1312 VE.incorporateFunction(F); 1313 1314 SmallVector<unsigned, 64> Vals; 1315 1316 // Emit the number of basic blocks, so the reader can create them ahead of 1317 // time. 1318 Vals.push_back(VE.getBasicBlocks().size()); 1319 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 1320 Vals.clear(); 1321 1322 // If there are function-local constants, emit them now. 1323 unsigned CstStart, CstEnd; 1324 VE.getFunctionConstantRange(CstStart, CstEnd); 1325 WriteConstants(CstStart, CstEnd, VE, Stream, false); 1326 1327 // If there is function-local metadata, emit it now. 1328 WriteFunctionLocalMetadata(F, VE, Stream); 1329 1330 // Keep a running idea of what the instruction ID is. 1331 unsigned InstID = CstEnd; 1332 1333 bool NeedsMetadataAttachment = false; 1334 1335 DebugLoc LastDL; 1336 1337 // Finally, emit all the instructions, in order. 1338 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 1339 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 1340 I != E; ++I) { 1341 WriteInstruction(*I, InstID, VE, Stream, Vals); 1342 1343 if (!I->getType()->isVoidTy()) 1344 ++InstID; 1345 1346 // If the instruction has metadata, write a metadata attachment later. 1347 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 1348 1349 // If the instruction has a debug location, emit it. 1350 DebugLoc DL = I->getDebugLoc(); 1351 if (DL.isUnknown()) { 1352 // nothing todo. 1353 } else if (DL == LastDL) { 1354 // Just repeat the same debug loc as last time. 1355 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 1356 } else { 1357 MDNode *Scope, *IA; 1358 DL.getScopeAndInlinedAt(Scope, IA, I->getContext()); 1359 1360 Vals.push_back(DL.getLine()); 1361 Vals.push_back(DL.getCol()); 1362 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0); 1363 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0); 1364 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 1365 Vals.clear(); 1366 1367 LastDL = DL; 1368 } 1369 } 1370 1371 // Emit names for all the instructions etc. 1372 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 1373 1374 if (NeedsMetadataAttachment) 1375 WriteMetadataAttachment(F, VE, Stream); 1376 VE.purgeFunction(); 1377 Stream.ExitBlock(); 1378} 1379 1380// Emit blockinfo, which defines the standard abbreviations etc. 1381static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { 1382 // We only want to emit block info records for blocks that have multiple 1383 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other 1384 // blocks can defined their abbrevs inline. 1385 Stream.EnterBlockInfoBlock(2); 1386 1387 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. 1388 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 1390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1392 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1393 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1394 Abbv) != VST_ENTRY_8_ABBREV) 1395 llvm_unreachable("Unexpected abbrev ordering!"); 1396 } 1397 1398 { // 7-bit fixed width VST_ENTRY strings. 1399 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1400 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 1401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1402 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1403 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1404 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1405 Abbv) != VST_ENTRY_7_ABBREV) 1406 llvm_unreachable("Unexpected abbrev ordering!"); 1407 } 1408 { // 6-bit char6 VST_ENTRY strings. 1409 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1410 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 1411 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1412 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1413 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1414 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1415 Abbv) != VST_ENTRY_6_ABBREV) 1416 llvm_unreachable("Unexpected abbrev ordering!"); 1417 } 1418 { // 6-bit char6 VST_BBENTRY strings. 1419 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1420 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 1421 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1422 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1423 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1424 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1425 Abbv) != VST_BBENTRY_6_ABBREV) 1426 llvm_unreachable("Unexpected abbrev ordering!"); 1427 } 1428 1429 1430 1431 { // SETTYPE abbrev for CONSTANTS_BLOCK. 1432 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1433 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 1434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1435 Log2_32_Ceil(VE.getTypes().size()+1))); 1436 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1437 Abbv) != CONSTANTS_SETTYPE_ABBREV) 1438 llvm_unreachable("Unexpected abbrev ordering!"); 1439 } 1440 1441 { // INTEGER abbrev for CONSTANTS_BLOCK. 1442 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1443 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 1444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1445 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1446 Abbv) != CONSTANTS_INTEGER_ABBREV) 1447 llvm_unreachable("Unexpected abbrev ordering!"); 1448 } 1449 1450 { // CE_CAST abbrev for CONSTANTS_BLOCK. 1451 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1452 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 1453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 1454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 1455 Log2_32_Ceil(VE.getTypes().size()+1))); 1456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 1457 1458 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1459 Abbv) != CONSTANTS_CE_CAST_Abbrev) 1460 llvm_unreachable("Unexpected abbrev ordering!"); 1461 } 1462 { // NULL abbrev for CONSTANTS_BLOCK. 1463 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1464 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 1465 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1466 Abbv) != CONSTANTS_NULL_Abbrev) 1467 llvm_unreachable("Unexpected abbrev ordering!"); 1468 } 1469 1470 // FIXME: This should only use space for first class types! 1471 1472 { // INST_LOAD abbrev for FUNCTION_BLOCK. 1473 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1474 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 1475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 1476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 1477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 1478 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1479 Abbv) != FUNCTION_INST_LOAD_ABBREV) 1480 llvm_unreachable("Unexpected abbrev ordering!"); 1481 } 1482 { // INST_BINOP abbrev for FUNCTION_BLOCK. 1483 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1484 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 1485 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 1486 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 1487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1488 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1489 Abbv) != FUNCTION_INST_BINOP_ABBREV) 1490 llvm_unreachable("Unexpected abbrev ordering!"); 1491 } 1492 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 1493 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1494 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 1495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 1496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 1497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 1499 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1500 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV) 1501 llvm_unreachable("Unexpected abbrev ordering!"); 1502 } 1503 { // INST_CAST abbrev for FUNCTION_BLOCK. 1504 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1505 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 1506 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 1507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 1508 Log2_32_Ceil(VE.getTypes().size()+1))); 1509 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1510 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1511 Abbv) != FUNCTION_INST_CAST_ABBREV) 1512 llvm_unreachable("Unexpected abbrev ordering!"); 1513 } 1514 1515 { // INST_RET abbrev for FUNCTION_BLOCK. 1516 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1517 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 1518 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1519 Abbv) != FUNCTION_INST_RET_VOID_ABBREV) 1520 llvm_unreachable("Unexpected abbrev ordering!"); 1521 } 1522 { // INST_RET abbrev for FUNCTION_BLOCK. 1523 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1524 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 1525 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 1526 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1527 Abbv) != FUNCTION_INST_RET_VAL_ABBREV) 1528 llvm_unreachable("Unexpected abbrev ordering!"); 1529 } 1530 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 1531 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1532 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 1533 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1534 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV) 1535 llvm_unreachable("Unexpected abbrev ordering!"); 1536 } 1537 1538 Stream.ExitBlock(); 1539} 1540 1541 1542/// WriteModule - Emit the specified module to the bitstream. 1543static void WriteModule(const Module *M, BitstreamWriter &Stream) { 1544 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 1545 1546 // Emit the version number if it is non-zero. 1547 if (CurVersion) { 1548 SmallVector<unsigned, 1> Vals; 1549 Vals.push_back(CurVersion); 1550 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 1551 } 1552 1553 // Analyze the module, enumerating globals, functions, etc. 1554 ValueEnumerator VE(M); 1555 1556 // Emit blockinfo, which defines the standard abbreviations etc. 1557 WriteBlockInfo(VE, Stream); 1558 1559 // Emit information about parameter attributes. 1560 WriteAttributeTable(VE, Stream); 1561 1562 // Emit information describing all of the types in the module. 1563 WriteTypeTable(VE, Stream); 1564 1565 // Emit top-level description of module, including target triple, inline asm, 1566 // descriptors for global variables, and function prototype info. 1567 WriteModuleInfo(M, VE, Stream); 1568 1569 // Emit constants. 1570 WriteModuleConstants(VE, Stream); 1571 1572 // Emit metadata. 1573 WriteModuleMetadata(M, VE, Stream); 1574 1575 // Emit function bodies. 1576 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) 1577 if (!F->isDeclaration()) 1578 WriteFunction(*F, VE, Stream); 1579 1580 // Emit metadata. 1581 WriteModuleMetadataStore(M, Stream); 1582 1583 // Emit names for globals/functions etc. 1584 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); 1585 1586 Stream.ExitBlock(); 1587} 1588 1589/// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a 1590/// header and trailer to make it compatible with the system archiver. To do 1591/// this we emit the following header, and then emit a trailer that pads the 1592/// file out to be a multiple of 16 bytes. 1593/// 1594/// struct bc_header { 1595/// uint32_t Magic; // 0x0B17C0DE 1596/// uint32_t Version; // Version, currently always 0. 1597/// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 1598/// uint32_t BitcodeSize; // Size of traditional bitcode file. 1599/// uint32_t CPUType; // CPU specifier. 1600/// ... potentially more later ... 1601/// }; 1602enum { 1603 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size. 1604 DarwinBCHeaderSize = 5*4 1605}; 1606 1607static void EmitDarwinBCHeader(BitstreamWriter &Stream, const Triple &TT) { 1608 unsigned CPUType = ~0U; 1609 1610 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 1611 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 1612 // number from /usr/include/mach/machine.h. It is ok to reproduce the 1613 // specific constants here because they are implicitly part of the Darwin ABI. 1614 enum { 1615 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 1616 DARWIN_CPU_TYPE_X86 = 7, 1617 DARWIN_CPU_TYPE_ARM = 12, 1618 DARWIN_CPU_TYPE_POWERPC = 18 1619 }; 1620 1621 Triple::ArchType Arch = TT.getArch(); 1622 if (Arch == Triple::x86_64) 1623 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 1624 else if (Arch == Triple::x86) 1625 CPUType = DARWIN_CPU_TYPE_X86; 1626 else if (Arch == Triple::ppc) 1627 CPUType = DARWIN_CPU_TYPE_POWERPC; 1628 else if (Arch == Triple::ppc64) 1629 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 1630 else if (Arch == Triple::arm || Arch == Triple::thumb) 1631 CPUType = DARWIN_CPU_TYPE_ARM; 1632 1633 // Traditional Bitcode starts after header. 1634 unsigned BCOffset = DarwinBCHeaderSize; 1635 1636 Stream.Emit(0x0B17C0DE, 32); 1637 Stream.Emit(0 , 32); // Version. 1638 Stream.Emit(BCOffset , 32); 1639 Stream.Emit(0 , 32); // Filled in later. 1640 Stream.Emit(CPUType , 32); 1641} 1642 1643/// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and 1644/// finalize the header. 1645static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) { 1646 // Update the size field in the header. 1647 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize); 1648 1649 // If the file is not a multiple of 16 bytes, insert dummy padding. 1650 while (BufferSize & 15) { 1651 Stream.Emit(0, 8); 1652 ++BufferSize; 1653 } 1654} 1655 1656 1657/// WriteBitcodeToFile - Write the specified module to the specified output 1658/// stream. 1659void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) { 1660 std::vector<unsigned char> Buffer; 1661 BitstreamWriter Stream(Buffer); 1662 1663 Buffer.reserve(256*1024); 1664 1665 WriteBitcodeToStream( M, Stream ); 1666 1667 // Write the generated bitstream to "Out". 1668 Out.write((char*)&Buffer.front(), Buffer.size()); 1669} 1670 1671/// WriteBitcodeToStream - Write the specified module to the specified output 1672/// stream. 1673void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) { 1674 // If this is darwin or another generic macho target, emit a file header and 1675 // trailer if needed. 1676 Triple TT(M->getTargetTriple()); 1677 if (TT.isOSDarwin()) 1678 EmitDarwinBCHeader(Stream, TT); 1679 1680 // Emit the file header. 1681 Stream.Emit((unsigned)'B', 8); 1682 Stream.Emit((unsigned)'C', 8); 1683 Stream.Emit(0x0, 4); 1684 Stream.Emit(0xC, 4); 1685 Stream.Emit(0xE, 4); 1686 Stream.Emit(0xD, 4); 1687 1688 // Emit the module. 1689 WriteModule(M, Stream); 1690 1691 if (TT.isOSDarwin()) 1692 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size()); 1693} 1694