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