1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by Chris Lattner and is distributed under 6 // the University of Illinois Open Source 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/Instructions.h" 21 #include "llvm/Module.h" 22 #include "llvm/ParameterAttributes.h" 23 #include "llvm/TypeSymbolTable.h" 24 #include "llvm/ValueSymbolTable.h" 25 #include "llvm/Support/MathExtras.h" 26 using namespace llvm; 27 28 static const unsigned CurVersion = 0; 29 30 static unsigned GetEncodedCastOpcode(unsigned Opcode) { 31 switch (Opcode) { 32 default: assert(0 && "Unknown cast instruction!"); 33 case Instruction::Trunc : return bitc::CAST_TRUNC; 34 case Instruction::ZExt : return bitc::CAST_ZEXT; 35 case Instruction::SExt : return bitc::CAST_SEXT; 36 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 37 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 38 case Instruction::UIToFP : return bitc::CAST_UITOFP; 39 case Instruction::SIToFP : return bitc::CAST_SITOFP; 40 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 41 case Instruction::FPExt : return bitc::CAST_FPEXT; 42 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 43 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 44 case Instruction::BitCast : return bitc::CAST_BITCAST; 45 } 46 } 47 48 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 49 switch (Opcode) { 50 default: assert(0 && "Unknown binary instruction!"); 51 case Instruction::Add: return bitc::BINOP_ADD; 52 case Instruction::Sub: return bitc::BINOP_SUB; 53 case Instruction::Mul: return bitc::BINOP_MUL; 54 case Instruction::UDiv: return bitc::BINOP_UDIV; 55 case Instruction::FDiv: 56 case Instruction::SDiv: return bitc::BINOP_SDIV; 57 case Instruction::URem: return bitc::BINOP_UREM; 58 case Instruction::FRem: 59 case Instruction::SRem: return bitc::BINOP_SREM; 60 case Instruction::Shl: return bitc::BINOP_SHL; 61 case Instruction::LShr: return bitc::BINOP_LSHR; 62 case Instruction::AShr: return bitc::BINOP_ASHR; 63 case Instruction::And: return bitc::BINOP_AND; 64 case Instruction::Or: return bitc::BINOP_OR; 65 case Instruction::Xor: return bitc::BINOP_XOR; 66 } 67 } 68 69 70 71 static void WriteStringRecord(unsigned Code, const std::string &Str, 72 unsigned AbbrevToUse, BitstreamWriter &Stream) { 73 SmallVector<unsigned, 64> Vals; 74 75 // Code: [strchar x N] 76 for (unsigned i = 0, e = Str.size(); i != e; ++i) 77 Vals.push_back(Str[i]); 78 79 // Emit the finished record. 80 Stream.EmitRecord(Code, Vals, AbbrevToUse); 81 } 82 83 // Emit information about parameter attributes. 84 static void WriteParamAttrTable(const ValueEnumerator &VE, 85 BitstreamWriter &Stream) { 86 const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs(); 87 if (Attrs.empty()) return; 88 89 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 90 91 SmallVector<uint64_t, 64> Record; 92 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 93 const ParamAttrsList *A = Attrs[i]; 94 for (unsigned op = 0, e = A->size(); op != e; ++op) { 95 Record.push_back(A->getParamIndex(op)); 96 Record.push_back(A->getParamAttrsAtIndex(op)); 97 } 98 99 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 100 Record.clear(); 101 } 102 103 Stream.ExitBlock(); 104 } 105 106 /// WriteTypeTable - Write out the type table for a module. 107 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 108 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 109 110 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */); 111 SmallVector<uint64_t, 64> TypeVals; 112 113 // FIXME: Set up abbrevs now that we know the width of the type fields, etc. 114 115 // Emit an entry count so the reader can reserve space. 116 TypeVals.push_back(TypeList.size()); 117 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 118 TypeVals.clear(); 119 120 // Loop over all of the types, emitting each in turn. 121 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 122 const Type *T = TypeList[i].first; 123 int AbbrevToUse = 0; 124 unsigned Code = 0; 125 126 switch (T->getTypeID()) { 127 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID. 128 default: assert(0 && "Unknown type!"); 129 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 130 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 131 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 132 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 133 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break; 134 case Type::IntegerTyID: 135 // INTEGER: [width] 136 Code = bitc::TYPE_CODE_INTEGER; 137 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 138 break; 139 case Type::PointerTyID: 140 // POINTER: [pointee type] 141 Code = bitc::TYPE_CODE_POINTER; 142 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType())); 143 break; 144 145 case Type::FunctionTyID: { 146 const FunctionType *FT = cast<FunctionType>(T); 147 // FUNCTION: [isvararg, attrid, #pararms, paramty x N] 148 Code = bitc::TYPE_CODE_FUNCTION; 149 TypeVals.push_back(FT->isVarArg()); 150 TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs())); 151 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 152 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 153 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 154 break; 155 } 156 case Type::StructTyID: { 157 const StructType *ST = cast<StructType>(T); 158 // STRUCT: [ispacked, #elts, eltty x N] 159 Code = bitc::TYPE_CODE_STRUCT; 160 TypeVals.push_back(ST->isPacked()); 161 // Output all of the element types. 162 for (StructType::element_iterator I = ST->element_begin(), 163 E = ST->element_end(); I != E; ++I) 164 TypeVals.push_back(VE.getTypeID(*I)); 165 break; 166 } 167 case Type::ArrayTyID: { 168 const ArrayType *AT = cast<ArrayType>(T); 169 // ARRAY: [numelts, eltty] 170 Code = bitc::TYPE_CODE_ARRAY; 171 TypeVals.push_back(AT->getNumElements()); 172 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 173 break; 174 } 175 case Type::VectorTyID: { 176 const VectorType *VT = cast<VectorType>(T); 177 // VECTOR [numelts, eltty] 178 Code = bitc::TYPE_CODE_VECTOR; 179 TypeVals.push_back(VT->getNumElements()); 180 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 181 break; 182 } 183 } 184 185 // Emit the finished record. 186 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 187 TypeVals.clear(); 188 } 189 190 Stream.ExitBlock(); 191 } 192 193 static unsigned getEncodedLinkage(const GlobalValue *GV) { 194 switch (GV->getLinkage()) { 195 default: assert(0 && "Invalid linkage!"); 196 case GlobalValue::ExternalLinkage: return 0; 197 case GlobalValue::WeakLinkage: return 1; 198 case GlobalValue::AppendingLinkage: return 2; 199 case GlobalValue::InternalLinkage: return 3; 200 case GlobalValue::LinkOnceLinkage: return 4; 201 case GlobalValue::DLLImportLinkage: return 5; 202 case GlobalValue::DLLExportLinkage: return 6; 203 case GlobalValue::ExternalWeakLinkage: return 7; 204 } 205 } 206 207 static unsigned getEncodedVisibility(const GlobalValue *GV) { 208 switch (GV->getVisibility()) { 209 default: assert(0 && "Invalid visibility!"); 210 case GlobalValue::DefaultVisibility: return 0; 211 case GlobalValue::HiddenVisibility: return 1; 212 case GlobalValue::ProtectedVisibility: return 2; 213 } 214 } 215 216 // Emit top-level description of module, including target triple, inline asm, 217 // descriptors for global variables, and function prototype info. 218 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 219 BitstreamWriter &Stream) { 220 // Emit the list of dependent libraries for the Module. 221 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I) 222 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream); 223 224 // Emit various pieces of data attached to a module. 225 if (!M->getTargetTriple().empty()) 226 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 227 0/*TODO*/, Stream); 228 if (!M->getDataLayout().empty()) 229 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(), 230 0/*TODO*/, Stream); 231 if (!M->getModuleInlineAsm().empty()) 232 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 233 0/*TODO*/, Stream); 234 235 // Emit information about sections, computing how many there are. Also 236 // compute the maximum alignment value. 237 std::map<std::string, unsigned> SectionMap; 238 unsigned MaxAlignment = 0; 239 unsigned MaxGlobalType = 0; 240 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 241 GV != E; ++GV) { 242 MaxAlignment = std::max(MaxAlignment, GV->getAlignment()); 243 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType())); 244 245 if (!GV->hasSection()) continue; 246 // Give section names unique ID's. 247 unsigned &Entry = SectionMap[GV->getSection()]; 248 if (Entry != 0) continue; 249 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(), 250 0/*TODO*/, Stream); 251 Entry = SectionMap.size(); 252 } 253 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 254 MaxAlignment = std::max(MaxAlignment, F->getAlignment()); 255 if (!F->hasSection()) continue; 256 // Give section names unique ID's. 257 unsigned &Entry = SectionMap[F->getSection()]; 258 if (Entry != 0) continue; 259 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(), 260 0/*TODO*/, Stream); 261 Entry = SectionMap.size(); 262 } 263 264 // Emit abbrev for globals, now that we know # sections and max alignment. 265 unsigned SimpleGVarAbbrev = 0; 266 if (!M->global_empty()) { 267 // Add an abbrev for common globals with no visibility or thread localness. 268 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 269 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 271 Log2_32_Ceil(MaxGlobalType+1))); 272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant. 273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 274 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage. 275 if (MaxAlignment == 0) // Alignment. 276 Abbv->Add(BitCodeAbbrevOp(0)); 277 else { 278 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 280 Log2_32_Ceil(MaxEncAlignment+1))); 281 } 282 if (SectionMap.empty()) // Section. 283 Abbv->Add(BitCodeAbbrevOp(0)); 284 else 285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 286 Log2_32_Ceil(SectionMap.size()+1))); 287 // Don't bother emitting vis + thread local. 288 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 289 } 290 291 // Emit the global variable information. 292 SmallVector<unsigned, 64> Vals; 293 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 294 GV != E; ++GV) { 295 unsigned AbbrevToUse = 0; 296 297 // GLOBALVAR: [type, isconst, initid, 298 // linkage, alignment, section, visibility, threadlocal] 299 Vals.push_back(VE.getTypeID(GV->getType())); 300 Vals.push_back(GV->isConstant()); 301 Vals.push_back(GV->isDeclaration() ? 0 : 302 (VE.getValueID(GV->getInitializer()) + 1)); 303 Vals.push_back(getEncodedLinkage(GV)); 304 Vals.push_back(Log2_32(GV->getAlignment())+1); 305 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0); 306 if (GV->isThreadLocal() || 307 GV->getVisibility() != GlobalValue::DefaultVisibility) { 308 Vals.push_back(getEncodedVisibility(GV)); 309 Vals.push_back(GV->isThreadLocal()); 310 } else { 311 AbbrevToUse = SimpleGVarAbbrev; 312 } 313 314 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 315 Vals.clear(); 316 } 317 318 // Emit the function proto information. 319 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 320 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section, 321 // visibility] 322 Vals.push_back(VE.getTypeID(F->getType())); 323 Vals.push_back(F->getCallingConv()); 324 Vals.push_back(F->isDeclaration()); 325 Vals.push_back(getEncodedLinkage(F)); 326 Vals.push_back(Log2_32(F->getAlignment())+1); 327 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0); 328 Vals.push_back(getEncodedVisibility(F)); 329 330 unsigned AbbrevToUse = 0; 331 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 332 Vals.clear(); 333 } 334 335 336 // Emit the alias information. 337 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); 338 AI != E; ++AI) { 339 Vals.push_back(VE.getTypeID(AI->getType())); 340 Vals.push_back(VE.getValueID(AI->getAliasee())); 341 Vals.push_back(getEncodedLinkage(AI)); 342 unsigned AbbrevToUse = 0; 343 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 344 Vals.clear(); 345 } 346 } 347 348 349 static void WriteConstants(unsigned FirstVal, unsigned LastVal, 350 const ValueEnumerator &VE, 351 BitstreamWriter &Stream) { 352 if (FirstVal == LastVal) return; 353 354 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2); 355 356 // FIXME: Install and use abbrevs to reduce size. Install them globally so 357 // they don't need to be reemitted for each function body. 358 359 SmallVector<uint64_t, 64> Record; 360 361 const ValueEnumerator::ValueList &Vals = VE.getValues(); 362 const Type *LastTy = 0; 363 for (unsigned i = FirstVal; i != LastVal; ++i) { 364 const Value *V = Vals[i].first; 365 // If we need to switch types, do so now. 366 if (V->getType() != LastTy) { 367 LastTy = V->getType(); 368 Record.push_back(VE.getTypeID(LastTy)); 369 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record); 370 Record.clear(); 371 } 372 373 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 374 assert(0 && IA && "FIXME: Inline asm writing unimp!"); 375 continue; 376 } 377 const Constant *C = cast<Constant>(V); 378 unsigned Code = -1U; 379 unsigned AbbrevToUse = 0; 380 if (C->isNullValue()) { 381 Code = bitc::CST_CODE_NULL; 382 } else if (isa<UndefValue>(C)) { 383 Code = bitc::CST_CODE_UNDEF; 384 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 385 if (IV->getBitWidth() <= 64) { 386 int64_t V = IV->getSExtValue(); 387 if (V >= 0) 388 Record.push_back(V << 1); 389 else 390 Record.push_back((-V << 1) | 1); 391 Code = bitc::CST_CODE_INTEGER; 392 } else { // Wide integers, > 64 bits in size. 393 // We have an arbitrary precision integer value to write whose 394 // bit width is > 64. However, in canonical unsigned integer 395 // format it is likely that the high bits are going to be zero. 396 // So, we only write the number of active words. 397 unsigned NWords = IV->getValue().getActiveWords(); 398 const uint64_t *RawWords = IV->getValue().getRawData(); 399 for (unsigned i = 0; i != NWords; ++i) { 400 int64_t V = RawWords[i]; 401 if (V >= 0) 402 Record.push_back(V << 1); 403 else 404 Record.push_back((-V << 1) | 1); 405 } 406 Code = bitc::CST_CODE_WIDE_INTEGER; 407 } 408 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 409 Code = bitc::CST_CODE_FLOAT; 410 if (CFP->getType() == Type::FloatTy) { 411 Record.push_back(FloatToBits((float)CFP->getValue())); 412 } else { 413 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!"); 414 Record.push_back(DoubleToBits((double)CFP->getValue())); 415 } 416 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) || 417 isa<ConstantVector>(V)) { 418 Code = bitc::CST_CODE_AGGREGATE; 419 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) 420 Record.push_back(VE.getValueID(C->getOperand(i))); 421 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 422 switch (CE->getOpcode()) { 423 default: 424 if (Instruction::isCast(CE->getOpcode())) { 425 Code = bitc::CST_CODE_CE_CAST; 426 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 427 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 428 Record.push_back(VE.getValueID(C->getOperand(0))); 429 } else { 430 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 431 Code = bitc::CST_CODE_CE_BINOP; 432 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 433 Record.push_back(VE.getValueID(C->getOperand(0))); 434 Record.push_back(VE.getValueID(C->getOperand(1))); 435 } 436 break; 437 case Instruction::GetElementPtr: 438 Code = bitc::CST_CODE_CE_GEP; 439 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 440 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 441 Record.push_back(VE.getValueID(C->getOperand(i))); 442 } 443 break; 444 case Instruction::Select: 445 Code = bitc::CST_CODE_CE_SELECT; 446 Record.push_back(VE.getValueID(C->getOperand(0))); 447 Record.push_back(VE.getValueID(C->getOperand(1))); 448 Record.push_back(VE.getValueID(C->getOperand(2))); 449 break; 450 case Instruction::ExtractElement: 451 Code = bitc::CST_CODE_CE_EXTRACTELT; 452 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 453 Record.push_back(VE.getValueID(C->getOperand(0))); 454 Record.push_back(VE.getValueID(C->getOperand(1))); 455 break; 456 case Instruction::InsertElement: 457 Code = bitc::CST_CODE_CE_INSERTELT; 458 Record.push_back(VE.getValueID(C->getOperand(0))); 459 Record.push_back(VE.getValueID(C->getOperand(1))); 460 Record.push_back(VE.getValueID(C->getOperand(2))); 461 break; 462 case Instruction::ShuffleVector: 463 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 464 Record.push_back(VE.getValueID(C->getOperand(0))); 465 Record.push_back(VE.getValueID(C->getOperand(1))); 466 Record.push_back(VE.getValueID(C->getOperand(2))); 467 break; 468 case Instruction::ICmp: 469 case Instruction::FCmp: 470 Code = bitc::CST_CODE_CE_CMP; 471 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 472 Record.push_back(VE.getValueID(C->getOperand(0))); 473 Record.push_back(VE.getValueID(C->getOperand(1))); 474 Record.push_back(CE->getPredicate()); 475 break; 476 } 477 } else { 478 assert(0 && "Unknown constant!"); 479 } 480 Stream.EmitRecord(Code, Record, AbbrevToUse); 481 Record.clear(); 482 } 483 484 Stream.ExitBlock(); 485 } 486 487 static void WriteModuleConstants(const ValueEnumerator &VE, 488 BitstreamWriter &Stream) { 489 const ValueEnumerator::ValueList &Vals = VE.getValues(); 490 491 // Find the first constant to emit, which is the first non-globalvalue value. 492 // We know globalvalues have been emitted by WriteModuleInfo. 493 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 494 if (!isa<GlobalValue>(Vals[i].first)) { 495 WriteConstants(i, Vals.size(), VE, Stream); 496 return; 497 } 498 } 499 } 500 501 /// WriteInstruction - Emit an instruction to the specified stream. 502 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE, 503 BitstreamWriter &Stream, 504 SmallVector<unsigned, 64> &Vals) { 505 unsigned Code = 0; 506 unsigned AbbrevToUse = 0; 507 switch (I.getOpcode()) { 508 default: 509 if (Instruction::isCast(I.getOpcode())) { 510 Code = bitc::FUNC_CODE_INST_CAST; 511 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 512 Vals.push_back(VE.getTypeID(I.getType())); 513 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 514 Vals.push_back(VE.getValueID(I.getOperand(0))); 515 } else { 516 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 517 Code = bitc::FUNC_CODE_INST_BINOP; 518 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 519 Vals.push_back(VE.getTypeID(I.getType())); 520 Vals.push_back(VE.getValueID(I.getOperand(0))); 521 Vals.push_back(VE.getValueID(I.getOperand(1))); 522 } 523 break; 524 525 case Instruction::GetElementPtr: 526 Code = bitc::FUNC_CODE_INST_GEP; 527 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 528 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType())); 529 Vals.push_back(VE.getValueID(I.getOperand(i))); 530 } 531 break; 532 case Instruction::Select: 533 Code = bitc::FUNC_CODE_INST_SELECT; 534 Vals.push_back(VE.getTypeID(I.getType())); 535 Vals.push_back(VE.getValueID(I.getOperand(0))); 536 Vals.push_back(VE.getValueID(I.getOperand(1))); 537 Vals.push_back(VE.getValueID(I.getOperand(2))); 538 break; 539 case Instruction::ExtractElement: 540 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 541 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 542 Vals.push_back(VE.getValueID(I.getOperand(0))); 543 Vals.push_back(VE.getValueID(I.getOperand(1))); 544 break; 545 case Instruction::InsertElement: 546 Code = bitc::FUNC_CODE_INST_INSERTELT; 547 Vals.push_back(VE.getTypeID(I.getType())); 548 Vals.push_back(VE.getValueID(I.getOperand(0))); 549 Vals.push_back(VE.getValueID(I.getOperand(1))); 550 Vals.push_back(VE.getValueID(I.getOperand(2))); 551 break; 552 case Instruction::ShuffleVector: 553 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 554 Vals.push_back(VE.getTypeID(I.getType())); 555 Vals.push_back(VE.getValueID(I.getOperand(0))); 556 Vals.push_back(VE.getValueID(I.getOperand(1))); 557 Vals.push_back(VE.getValueID(I.getOperand(2))); 558 break; 559 case Instruction::ICmp: 560 case Instruction::FCmp: 561 Code = bitc::FUNC_CODE_INST_CMP; 562 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 563 Vals.push_back(VE.getValueID(I.getOperand(0))); 564 Vals.push_back(VE.getValueID(I.getOperand(1))); 565 Vals.push_back(cast<CmpInst>(I).getPredicate()); 566 break; 567 568 case Instruction::Ret: 569 Code = bitc::FUNC_CODE_INST_RET; 570 if (I.getNumOperands()) { 571 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 572 Vals.push_back(VE.getValueID(I.getOperand(0))); 573 } 574 break; 575 case Instruction::Br: 576 Code = bitc::FUNC_CODE_INST_BR; 577 Vals.push_back(VE.getValueID(I.getOperand(0))); 578 if (cast<BranchInst>(I).isConditional()) { 579 Vals.push_back(VE.getValueID(I.getOperand(1))); 580 Vals.push_back(VE.getValueID(I.getOperand(2))); 581 } 582 break; 583 case Instruction::Switch: 584 Code = bitc::FUNC_CODE_INST_SWITCH; 585 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 586 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 587 Vals.push_back(VE.getValueID(I.getOperand(i))); 588 break; 589 case Instruction::Invoke: { 590 Code = bitc::FUNC_CODE_INST_INVOKE; 591 Vals.push_back(cast<InvokeInst>(I).getCallingConv()); 592 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 593 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee 594 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal 595 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind 596 597 // Emit value #'s for the fixed parameters. 598 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType()); 599 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 600 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 601 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param. 602 603 // Emit type/value pairs for varargs params. 604 if (FTy->isVarArg()) { 605 unsigned NumVarargs = I.getNumOperands()-3-FTy->getNumParams(); 606 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands(); 607 i != e; ++i) { 608 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType())); 609 Vals.push_back(VE.getValueID(I.getOperand(i))); 610 } 611 } 612 break; 613 } 614 case Instruction::Unwind: 615 Code = bitc::FUNC_CODE_INST_UNWIND; 616 break; 617 case Instruction::Unreachable: 618 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 619 break; 620 621 case Instruction::PHI: 622 Code = bitc::FUNC_CODE_INST_PHI; 623 Vals.push_back(VE.getTypeID(I.getType())); 624 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 625 Vals.push_back(VE.getValueID(I.getOperand(i))); 626 break; 627 628 case Instruction::Malloc: 629 Code = bitc::FUNC_CODE_INST_MALLOC; 630 Vals.push_back(VE.getTypeID(I.getType())); 631 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 632 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1); 633 break; 634 635 case Instruction::Free: 636 Code = bitc::FUNC_CODE_INST_FREE; 637 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 638 Vals.push_back(VE.getValueID(I.getOperand(0))); 639 break; 640 641 case Instruction::Alloca: 642 Code = bitc::FUNC_CODE_INST_ALLOCA; 643 Vals.push_back(VE.getTypeID(I.getType())); 644 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 645 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1); 646 break; 647 648 case Instruction::Load: 649 Code = bitc::FUNC_CODE_INST_LOAD; 650 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 651 Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr. 652 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 653 Vals.push_back(cast<LoadInst>(I).isVolatile()); 654 break; 655 case Instruction::Store: 656 Code = bitc::FUNC_CODE_INST_STORE; 657 Vals.push_back(VE.getTypeID(I.getOperand(1)->getType())); // Pointer 658 Vals.push_back(VE.getValueID(I.getOperand(0))); // val. 659 Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr. 660 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 661 Vals.push_back(cast<StoreInst>(I).isVolatile()); 662 break; 663 case Instruction::Call: { 664 Code = bitc::FUNC_CODE_INST_CALL; 665 Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) | 666 cast<CallInst>(I).isTailCall()); 667 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 668 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee 669 670 // Emit value #'s for the fixed parameters. 671 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType()); 672 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 673 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 674 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param. 675 676 // Emit type/value pairs for varargs params. 677 if (FTy->isVarArg()) { 678 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams(); 679 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands(); 680 i != e; ++i) { 681 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType())); 682 Vals.push_back(VE.getValueID(I.getOperand(i))); 683 } 684 } 685 break; 686 } 687 case Instruction::VAArg: 688 Code = bitc::FUNC_CODE_INST_VAARG; 689 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 690 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist. 691 Vals.push_back(VE.getTypeID(I.getType())); // restype. 692 break; 693 } 694 695 Stream.EmitRecord(Code, Vals, AbbrevToUse); 696 Vals.clear(); 697 } 698 699 // Emit names for globals/functions etc. 700 static void WriteValueSymbolTable(const ValueSymbolTable &VST, 701 const ValueEnumerator &VE, 702 BitstreamWriter &Stream) { 703 if (VST.empty()) return; 704 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3); 705 706 #if 0 707 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 708 Abbv->Add(BitCodeAbbrevOp(bitc::VST_ENTRY)); 709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 710 Log2_32_Ceil(MaxGlobalType+1))); 711 // Don't bother emitting vis + thread local. 712 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 713 #endif 714 715 716 // FIXME: Set up the abbrev, we know how many values there are! 717 // FIXME: We know if the type names can use 7-bit ascii. 718 SmallVector<unsigned, 64> NameVals; 719 720 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); 721 SI != SE; ++SI) { 722 unsigned AbbrevToUse = 0; 723 724 // VST_ENTRY: [valueid, namelen, namechar x N] 725 // VST_BBENTRY: [bbid, namelen, namechar x N] 726 unsigned Code; 727 if (isa<BasicBlock>(SI->getValue())) { 728 Code = bitc::VST_CODE_BBENTRY; 729 } else { 730 Code = bitc::VST_CODE_ENTRY; 731 } 732 733 NameVals.push_back(VE.getValueID(SI->getValue())); 734 for (const char *P = SI->getKeyData(), 735 *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P) 736 NameVals.push_back((unsigned char)*P); 737 738 // Emit the finished record. 739 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 740 NameVals.clear(); 741 } 742 Stream.ExitBlock(); 743 } 744 745 /// WriteFunction - Emit a function body to the module stream. 746 static void WriteFunction(const Function &F, ValueEnumerator &VE, 747 BitstreamWriter &Stream) { 748 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3); 749 VE.incorporateFunction(F); 750 751 SmallVector<unsigned, 64> Vals; 752 753 // Emit the number of basic blocks, so the reader can create them ahead of 754 // time. 755 Vals.push_back(VE.getBasicBlocks().size()); 756 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 757 Vals.clear(); 758 759 // FIXME: Function attributes? 760 761 // If there are function-local constants, emit them now. 762 unsigned CstStart, CstEnd; 763 VE.getFunctionConstantRange(CstStart, CstEnd); 764 WriteConstants(CstStart, CstEnd, VE, Stream); 765 766 // Finally, emit all the instructions, in order. 767 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 768 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 769 WriteInstruction(*I, VE, Stream, Vals); 770 771 // Emit names for all the instructions etc. 772 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 773 774 VE.purgeFunction(); 775 Stream.ExitBlock(); 776 } 777 778 /// WriteTypeSymbolTable - Emit a block for the specified type symtab. 779 static void WriteTypeSymbolTable(const TypeSymbolTable &TST, 780 const ValueEnumerator &VE, 781 BitstreamWriter &Stream) { 782 if (TST.empty()) return; 783 784 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3); 785 786 // FIXME: Set up the abbrev, we know how many types there are! 787 // FIXME: We know if the type names can use 7-bit ascii. 788 789 SmallVector<unsigned, 64> NameVals; 790 791 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 792 TI != TE; ++TI) { 793 unsigned AbbrevToUse = 0; 794 795 // TST_ENTRY: [typeid, namelen, namechar x N] 796 NameVals.push_back(VE.getTypeID(TI->second)); 797 798 const std::string &Str = TI->first; 799 for (unsigned i = 0, e = Str.size(); i != e; ++i) 800 NameVals.push_back(Str[i]); 801 802 // Emit the finished record. 803 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse); 804 NameVals.clear(); 805 } 806 807 Stream.ExitBlock(); 808 } 809 810 811 /// WriteModule - Emit the specified module to the bitstream. 812 static void WriteModule(const Module *M, BitstreamWriter &Stream) { 813 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 814 815 // Emit the version number if it is non-zero. 816 if (CurVersion) { 817 SmallVector<unsigned, 1> Vals; 818 Vals.push_back(CurVersion); 819 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 820 } 821 822 // Analyze the module, enumerating globals, functions, etc. 823 ValueEnumerator VE(M); 824 825 // Emit information about parameter attributes. 826 WriteParamAttrTable(VE, Stream); 827 828 // Emit information describing all of the types in the module. 829 WriteTypeTable(VE, Stream); 830 831 // Emit top-level description of module, including target triple, inline asm, 832 // descriptors for global variables, and function prototype info. 833 WriteModuleInfo(M, VE, Stream); 834 835 // Emit constants. 836 WriteModuleConstants(VE, Stream); 837 838 // If we have any aggregate values in the value table, purge them - these can 839 // only be used to initialize global variables. Doing so makes the value 840 // namespace smaller for code in functions. 841 int NumNonAggregates = VE.PurgeAggregateValues(); 842 if (NumNonAggregates != -1) { 843 SmallVector<unsigned, 1> Vals; 844 Vals.push_back(NumNonAggregates); 845 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals); 846 } 847 848 // Emit function bodies. 849 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 850 if (!I->isDeclaration()) 851 WriteFunction(*I, VE, Stream); 852 853 // Emit the type symbol table information. 854 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream); 855 856 // Emit names for globals/functions etc. 857 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); 858 859 Stream.ExitBlock(); 860 } 861 862 // Emit blockinfo, which defines the standard abbreviations etc. 863 static void WriteBlockInfo(BitstreamWriter &Stream) { 864 // We only want to emit block info records for blocks that have multiple 865 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other 866 // blocks can defined their abbrevs inline. 867 Stream.EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2); 868 869 #if 0 870 // Configure TYPE_SYMTAB_BLOCK's. 871 872 // Add an abbrev for VST_ENTRY where the characters each fit in 7 bits. 873 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 874 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8); // Value ID 876 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage. 877 878 xxx = Stream.EmitAbbrev(Abbv); 879 #endif 880 Stream.ExitBlock(); 881 } 882 883 884 /// WriteBitcodeToFile - Write the specified module to the specified output 885 /// stream. 886 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) { 887 std::vector<unsigned char> Buffer; 888 BitstreamWriter Stream(Buffer); 889 890 Buffer.reserve(256*1024); 891 892 // Emit the file header. 893 Stream.Emit((unsigned)'B', 8); 894 Stream.Emit((unsigned)'C', 8); 895 Stream.Emit(0x0, 4); 896 Stream.Emit(0xC, 4); 897 Stream.Emit(0xE, 4); 898 Stream.Emit(0xD, 4); 899 900 // Emit blockinfo, which defines the standard abbreviations etc. 901 WriteBlockInfo(Stream); 902 903 // Emit the module. 904 WriteModule(M, Stream); 905 906 // Write the generated bitstream to "Out". 907 Out.write((char*)&Buffer.front(), Buffer.size()); 908 } 909