LLVM API Documentation
00001 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // Bitcode writer implementation. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/Bitcode/ReaderWriter.h" 00015 #include "ValueEnumerator.h" 00016 #include "llvm/ADT/Triple.h" 00017 #include "llvm/Bitcode/BitstreamWriter.h" 00018 #include "llvm/Bitcode/LLVMBitCodes.h" 00019 #include "llvm/IR/Constants.h" 00020 #include "llvm/IR/DerivedTypes.h" 00021 #include "llvm/IR/InlineAsm.h" 00022 #include "llvm/IR/Instructions.h" 00023 #include "llvm/IR/Module.h" 00024 #include "llvm/IR/Operator.h" 00025 #include "llvm/IR/ValueSymbolTable.h" 00026 #include "llvm/Support/CommandLine.h" 00027 #include "llvm/Support/ErrorHandling.h" 00028 #include "llvm/Support/MathExtras.h" 00029 #include "llvm/Support/Program.h" 00030 #include "llvm/Support/raw_ostream.h" 00031 #include <cctype> 00032 #include <map> 00033 using namespace llvm; 00034 00035 static cl::opt<bool> 00036 EnablePreserveUseListOrdering("enable-bc-uselist-preserve", 00037 cl::desc("Turn on experimental support for " 00038 "use-list order preservation."), 00039 cl::init(false), cl::Hidden); 00040 00041 /// These are manifest constants used by the bitcode writer. They do not need to 00042 /// be kept in sync with the reader, but need to be consistent within this file. 00043 enum { 00044 // VALUE_SYMTAB_BLOCK abbrev id's. 00045 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 00046 VST_ENTRY_7_ABBREV, 00047 VST_ENTRY_6_ABBREV, 00048 VST_BBENTRY_6_ABBREV, 00049 00050 // CONSTANTS_BLOCK abbrev id's. 00051 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 00052 CONSTANTS_INTEGER_ABBREV, 00053 CONSTANTS_CE_CAST_Abbrev, 00054 CONSTANTS_NULL_Abbrev, 00055 00056 // FUNCTION_BLOCK abbrev id's. 00057 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 00058 FUNCTION_INST_BINOP_ABBREV, 00059 FUNCTION_INST_BINOP_FLAGS_ABBREV, 00060 FUNCTION_INST_CAST_ABBREV, 00061 FUNCTION_INST_RET_VOID_ABBREV, 00062 FUNCTION_INST_RET_VAL_ABBREV, 00063 FUNCTION_INST_UNREACHABLE_ABBREV, 00064 00065 // SwitchInst Magic 00066 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 00067 }; 00068 00069 static unsigned GetEncodedCastOpcode(unsigned Opcode) { 00070 switch (Opcode) { 00071 default: llvm_unreachable("Unknown cast instruction!"); 00072 case Instruction::Trunc : return bitc::CAST_TRUNC; 00073 case Instruction::ZExt : return bitc::CAST_ZEXT; 00074 case Instruction::SExt : return bitc::CAST_SEXT; 00075 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 00076 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 00077 case Instruction::UIToFP : return bitc::CAST_UITOFP; 00078 case Instruction::SIToFP : return bitc::CAST_SITOFP; 00079 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 00080 case Instruction::FPExt : return bitc::CAST_FPEXT; 00081 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 00082 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 00083 case Instruction::BitCast : return bitc::CAST_BITCAST; 00084 } 00085 } 00086 00087 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 00088 switch (Opcode) { 00089 default: llvm_unreachable("Unknown binary instruction!"); 00090 case Instruction::Add: 00091 case Instruction::FAdd: return bitc::BINOP_ADD; 00092 case Instruction::Sub: 00093 case Instruction::FSub: return bitc::BINOP_SUB; 00094 case Instruction::Mul: 00095 case Instruction::FMul: return bitc::BINOP_MUL; 00096 case Instruction::UDiv: return bitc::BINOP_UDIV; 00097 case Instruction::FDiv: 00098 case Instruction::SDiv: return bitc::BINOP_SDIV; 00099 case Instruction::URem: return bitc::BINOP_UREM; 00100 case Instruction::FRem: 00101 case Instruction::SRem: return bitc::BINOP_SREM; 00102 case Instruction::Shl: return bitc::BINOP_SHL; 00103 case Instruction::LShr: return bitc::BINOP_LSHR; 00104 case Instruction::AShr: return bitc::BINOP_ASHR; 00105 case Instruction::And: return bitc::BINOP_AND; 00106 case Instruction::Or: return bitc::BINOP_OR; 00107 case Instruction::Xor: return bitc::BINOP_XOR; 00108 } 00109 } 00110 00111 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 00112 switch (Op) { 00113 default: llvm_unreachable("Unknown RMW operation!"); 00114 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 00115 case AtomicRMWInst::Add: return bitc::RMW_ADD; 00116 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 00117 case AtomicRMWInst::And: return bitc::RMW_AND; 00118 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 00119 case AtomicRMWInst::Or: return bitc::RMW_OR; 00120 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 00121 case AtomicRMWInst::Max: return bitc::RMW_MAX; 00122 case AtomicRMWInst::Min: return bitc::RMW_MIN; 00123 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 00124 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 00125 } 00126 } 00127 00128 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) { 00129 switch (Ordering) { 00130 case NotAtomic: return bitc::ORDERING_NOTATOMIC; 00131 case Unordered: return bitc::ORDERING_UNORDERED; 00132 case Monotonic: return bitc::ORDERING_MONOTONIC; 00133 case Acquire: return bitc::ORDERING_ACQUIRE; 00134 case Release: return bitc::ORDERING_RELEASE; 00135 case AcquireRelease: return bitc::ORDERING_ACQREL; 00136 case SequentiallyConsistent: return bitc::ORDERING_SEQCST; 00137 } 00138 llvm_unreachable("Invalid ordering"); 00139 } 00140 00141 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) { 00142 switch (SynchScope) { 00143 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD; 00144 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD; 00145 } 00146 llvm_unreachable("Invalid synch scope"); 00147 } 00148 00149 static void WriteStringRecord(unsigned Code, StringRef Str, 00150 unsigned AbbrevToUse, BitstreamWriter &Stream) { 00151 SmallVector<unsigned, 64> Vals; 00152 00153 // Code: [strchar x N] 00154 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 00155 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 00156 AbbrevToUse = 0; 00157 Vals.push_back(Str[i]); 00158 } 00159 00160 // Emit the finished record. 00161 Stream.EmitRecord(Code, Vals, AbbrevToUse); 00162 } 00163 00164 static void WriteAttributeGroupTable(const ValueEnumerator &VE, 00165 BitstreamWriter &Stream) { 00166 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups(); 00167 if (AttrGrps.empty()) return; 00168 00169 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 00170 00171 SmallVector<uint64_t, 64> Record; 00172 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) { 00173 AttributeSet AS = AttrGrps[i]; 00174 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) { 00175 AttributeSet A = AS.getSlotAttributes(i); 00176 00177 Record.push_back(VE.getAttributeGroupID(A)); 00178 Record.push_back(AS.getSlotIndex(i)); 00179 00180 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0); 00181 I != E; ++I) { 00182 Attribute Attr = *I; 00183 if (Attr.isEnumAttribute()) { 00184 Record.push_back(0); 00185 Record.push_back(Attr.getKindAsEnum()); 00186 } else if (Attr.isAlignAttribute()) { 00187 Record.push_back(1); 00188 Record.push_back(Attr.getKindAsEnum()); 00189 Record.push_back(Attr.getValueAsInt()); 00190 } else { 00191 StringRef Kind = Attr.getKindAsString(); 00192 StringRef Val = Attr.getValueAsString(); 00193 00194 Record.push_back(Val.empty() ? 3 : 4); 00195 Record.append(Kind.begin(), Kind.end()); 00196 Record.push_back(0); 00197 if (!Val.empty()) { 00198 Record.append(Val.begin(), Val.end()); 00199 Record.push_back(0); 00200 } 00201 } 00202 } 00203 00204 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 00205 Record.clear(); 00206 } 00207 } 00208 00209 Stream.ExitBlock(); 00210 } 00211 00212 static void WriteAttributeTable(const ValueEnumerator &VE, 00213 BitstreamWriter &Stream) { 00214 const std::vector<AttributeSet> &Attrs = VE.getAttributes(); 00215 if (Attrs.empty()) return; 00216 00217 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 00218 00219 SmallVector<uint64_t, 64> Record; 00220 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 00221 const AttributeSet &A = Attrs[i]; 00222 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) 00223 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i))); 00224 00225 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 00226 Record.clear(); 00227 } 00228 00229 Stream.ExitBlock(); 00230 } 00231 00232 /// WriteTypeTable - Write out the type table for a module. 00233 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 00234 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 00235 00236 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 00237 SmallVector<uint64_t, 64> TypeVals; 00238 00239 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1); 00240 00241 // Abbrev for TYPE_CODE_POINTER. 00242 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 00243 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 00244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 00245 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 00246 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv); 00247 00248 // Abbrev for TYPE_CODE_FUNCTION. 00249 Abbv = new BitCodeAbbrev(); 00250 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 00251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 00252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 00254 00255 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); 00256 00257 // Abbrev for TYPE_CODE_STRUCT_ANON. 00258 Abbv = new BitCodeAbbrev(); 00259 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 00260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 00261 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 00263 00264 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv); 00265 00266 // Abbrev for TYPE_CODE_STRUCT_NAME. 00267 Abbv = new BitCodeAbbrev(); 00268 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 00269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 00271 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv); 00272 00273 // Abbrev for TYPE_CODE_STRUCT_NAMED. 00274 Abbv = new BitCodeAbbrev(); 00275 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 00276 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 00277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 00279 00280 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv); 00281 00282 // Abbrev for TYPE_CODE_ARRAY. 00283 Abbv = new BitCodeAbbrev(); 00284 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 00285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 00286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 00287 00288 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); 00289 00290 // Emit an entry count so the reader can reserve space. 00291 TypeVals.push_back(TypeList.size()); 00292 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 00293 TypeVals.clear(); 00294 00295 // Loop over all of the types, emitting each in turn. 00296 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 00297 Type *T = TypeList[i]; 00298 int AbbrevToUse = 0; 00299 unsigned Code = 0; 00300 00301 switch (T->getTypeID()) { 00302 default: llvm_unreachable("Unknown type!"); 00303 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 00304 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 00305 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 00306 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 00307 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 00308 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 00309 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 00310 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 00311 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 00312 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 00313 case Type::IntegerTyID: 00314 // INTEGER: [width] 00315 Code = bitc::TYPE_CODE_INTEGER; 00316 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 00317 break; 00318 case Type::PointerTyID: { 00319 PointerType *PTy = cast<PointerType>(T); 00320 // POINTER: [pointee type, address space] 00321 Code = bitc::TYPE_CODE_POINTER; 00322 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 00323 unsigned AddressSpace = PTy->getAddressSpace(); 00324 TypeVals.push_back(AddressSpace); 00325 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 00326 break; 00327 } 00328 case Type::FunctionTyID: { 00329 FunctionType *FT = cast<FunctionType>(T); 00330 // FUNCTION: [isvararg, retty, paramty x N] 00331 Code = bitc::TYPE_CODE_FUNCTION; 00332 TypeVals.push_back(FT->isVarArg()); 00333 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 00334 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 00335 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 00336 AbbrevToUse = FunctionAbbrev; 00337 break; 00338 } 00339 case Type::StructTyID: { 00340 StructType *ST = cast<StructType>(T); 00341 // STRUCT: [ispacked, eltty x N] 00342 TypeVals.push_back(ST->isPacked()); 00343 // Output all of the element types. 00344 for (StructType::element_iterator I = ST->element_begin(), 00345 E = ST->element_end(); I != E; ++I) 00346 TypeVals.push_back(VE.getTypeID(*I)); 00347 00348 if (ST->isLiteral()) { 00349 Code = bitc::TYPE_CODE_STRUCT_ANON; 00350 AbbrevToUse = StructAnonAbbrev; 00351 } else { 00352 if (ST->isOpaque()) { 00353 Code = bitc::TYPE_CODE_OPAQUE; 00354 } else { 00355 Code = bitc::TYPE_CODE_STRUCT_NAMED; 00356 AbbrevToUse = StructNamedAbbrev; 00357 } 00358 00359 // Emit the name if it is present. 00360 if (!ST->getName().empty()) 00361 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 00362 StructNameAbbrev, Stream); 00363 } 00364 break; 00365 } 00366 case Type::ArrayTyID: { 00367 ArrayType *AT = cast<ArrayType>(T); 00368 // ARRAY: [numelts, eltty] 00369 Code = bitc::TYPE_CODE_ARRAY; 00370 TypeVals.push_back(AT->getNumElements()); 00371 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 00372 AbbrevToUse = ArrayAbbrev; 00373 break; 00374 } 00375 case Type::VectorTyID: { 00376 VectorType *VT = cast<VectorType>(T); 00377 // VECTOR [numelts, eltty] 00378 Code = bitc::TYPE_CODE_VECTOR; 00379 TypeVals.push_back(VT->getNumElements()); 00380 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 00381 break; 00382 } 00383 } 00384 00385 // Emit the finished record. 00386 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 00387 TypeVals.clear(); 00388 } 00389 00390 Stream.ExitBlock(); 00391 } 00392 00393 static unsigned getEncodedLinkage(const GlobalValue *GV) { 00394 switch (GV->getLinkage()) { 00395 case GlobalValue::ExternalLinkage: return 0; 00396 case GlobalValue::WeakAnyLinkage: return 1; 00397 case GlobalValue::AppendingLinkage: return 2; 00398 case GlobalValue::InternalLinkage: return 3; 00399 case GlobalValue::LinkOnceAnyLinkage: return 4; 00400 case GlobalValue::DLLImportLinkage: return 5; 00401 case GlobalValue::DLLExportLinkage: return 6; 00402 case GlobalValue::ExternalWeakLinkage: return 7; 00403 case GlobalValue::CommonLinkage: return 8; 00404 case GlobalValue::PrivateLinkage: return 9; 00405 case GlobalValue::WeakODRLinkage: return 10; 00406 case GlobalValue::LinkOnceODRLinkage: return 11; 00407 case GlobalValue::AvailableExternallyLinkage: return 12; 00408 case GlobalValue::LinkerPrivateLinkage: return 13; 00409 case GlobalValue::LinkerPrivateWeakLinkage: return 14; 00410 case GlobalValue::LinkOnceODRAutoHideLinkage: return 15; 00411 } 00412 llvm_unreachable("Invalid linkage"); 00413 } 00414 00415 static unsigned getEncodedVisibility(const GlobalValue *GV) { 00416 switch (GV->getVisibility()) { 00417 case GlobalValue::DefaultVisibility: return 0; 00418 case GlobalValue::HiddenVisibility: return 1; 00419 case GlobalValue::ProtectedVisibility: return 2; 00420 } 00421 llvm_unreachable("Invalid visibility"); 00422 } 00423 00424 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) { 00425 switch (GV->getThreadLocalMode()) { 00426 case GlobalVariable::NotThreadLocal: return 0; 00427 case GlobalVariable::GeneralDynamicTLSModel: return 1; 00428 case GlobalVariable::LocalDynamicTLSModel: return 2; 00429 case GlobalVariable::InitialExecTLSModel: return 3; 00430 case GlobalVariable::LocalExecTLSModel: return 4; 00431 } 00432 llvm_unreachable("Invalid TLS model"); 00433 } 00434 00435 // Emit top-level description of module, including target triple, inline asm, 00436 // descriptors for global variables, and function prototype info. 00437 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 00438 BitstreamWriter &Stream) { 00439 // Emit various pieces of data attached to a module. 00440 if (!M->getTargetTriple().empty()) 00441 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 00442 0/*TODO*/, Stream); 00443 if (!M->getDataLayout().empty()) 00444 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(), 00445 0/*TODO*/, Stream); 00446 if (!M->getModuleInlineAsm().empty()) 00447 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 00448 0/*TODO*/, Stream); 00449 00450 // Emit information about sections and GC, computing how many there are. Also 00451 // compute the maximum alignment value. 00452 std::map<std::string, unsigned> SectionMap; 00453 std::map<std::string, unsigned> GCMap; 00454 unsigned MaxAlignment = 0; 00455 unsigned MaxGlobalType = 0; 00456 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 00457 GV != E; ++GV) { 00458 MaxAlignment = std::max(MaxAlignment, GV->getAlignment()); 00459 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType())); 00460 if (GV->hasSection()) { 00461 // Give section names unique ID's. 00462 unsigned &Entry = SectionMap[GV->getSection()]; 00463 if (!Entry) { 00464 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(), 00465 0/*TODO*/, Stream); 00466 Entry = SectionMap.size(); 00467 } 00468 } 00469 } 00470 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 00471 MaxAlignment = std::max(MaxAlignment, F->getAlignment()); 00472 if (F->hasSection()) { 00473 // Give section names unique ID's. 00474 unsigned &Entry = SectionMap[F->getSection()]; 00475 if (!Entry) { 00476 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(), 00477 0/*TODO*/, Stream); 00478 Entry = SectionMap.size(); 00479 } 00480 } 00481 if (F->hasGC()) { 00482 // Same for GC names. 00483 unsigned &Entry = GCMap[F->getGC()]; 00484 if (!Entry) { 00485 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(), 00486 0/*TODO*/, Stream); 00487 Entry = GCMap.size(); 00488 } 00489 } 00490 } 00491 00492 // Emit abbrev for globals, now that we know # sections and max alignment. 00493 unsigned SimpleGVarAbbrev = 0; 00494 if (!M->global_empty()) { 00495 // Add an abbrev for common globals with no visibility or thread localness. 00496 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 00497 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 00498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 00499 Log2_32_Ceil(MaxGlobalType+1))); 00500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant. 00501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 00502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage. 00503 if (MaxAlignment == 0) // Alignment. 00504 Abbv->Add(BitCodeAbbrevOp(0)); 00505 else { 00506 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 00507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 00508 Log2_32_Ceil(MaxEncAlignment+1))); 00509 } 00510 if (SectionMap.empty()) // Section. 00511 Abbv->Add(BitCodeAbbrevOp(0)); 00512 else 00513 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 00514 Log2_32_Ceil(SectionMap.size()+1))); 00515 // Don't bother emitting vis + thread local. 00516 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 00517 } 00518 00519 // Emit the global variable information. 00520 SmallVector<unsigned, 64> Vals; 00521 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 00522 GV != E; ++GV) { 00523 unsigned AbbrevToUse = 0; 00524 00525 // GLOBALVAR: [type, isconst, initid, 00526 // linkage, alignment, section, visibility, threadlocal, 00527 // unnamed_addr] 00528 Vals.push_back(VE.getTypeID(GV->getType())); 00529 Vals.push_back(GV->isConstant()); 00530 Vals.push_back(GV->isDeclaration() ? 0 : 00531 (VE.getValueID(GV->getInitializer()) + 1)); 00532 Vals.push_back(getEncodedLinkage(GV)); 00533 Vals.push_back(Log2_32(GV->getAlignment())+1); 00534 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0); 00535 if (GV->isThreadLocal() || 00536 GV->getVisibility() != GlobalValue::DefaultVisibility || 00537 GV->hasUnnamedAddr() || GV->isExternallyInitialized()) { 00538 Vals.push_back(getEncodedVisibility(GV)); 00539 Vals.push_back(getEncodedThreadLocalMode(GV)); 00540 Vals.push_back(GV->hasUnnamedAddr()); 00541 Vals.push_back(GV->isExternallyInitialized()); 00542 } else { 00543 AbbrevToUse = SimpleGVarAbbrev; 00544 } 00545 00546 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 00547 Vals.clear(); 00548 } 00549 00550 // Emit the function proto information. 00551 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 00552 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 00553 // section, visibility, gc, unnamed_addr] 00554 Vals.push_back(VE.getTypeID(F->getType())); 00555 Vals.push_back(F->getCallingConv()); 00556 Vals.push_back(F->isDeclaration()); 00557 Vals.push_back(getEncodedLinkage(F)); 00558 Vals.push_back(VE.getAttributeID(F->getAttributes())); 00559 Vals.push_back(Log2_32(F->getAlignment())+1); 00560 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0); 00561 Vals.push_back(getEncodedVisibility(F)); 00562 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0); 00563 Vals.push_back(F->hasUnnamedAddr()); 00564 00565 unsigned AbbrevToUse = 0; 00566 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 00567 Vals.clear(); 00568 } 00569 00570 // Emit the alias information. 00571 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); 00572 AI != E; ++AI) { 00573 // ALIAS: [alias type, aliasee val#, linkage, visibility] 00574 Vals.push_back(VE.getTypeID(AI->getType())); 00575 Vals.push_back(VE.getValueID(AI->getAliasee())); 00576 Vals.push_back(getEncodedLinkage(AI)); 00577 Vals.push_back(getEncodedVisibility(AI)); 00578 unsigned AbbrevToUse = 0; 00579 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 00580 Vals.clear(); 00581 } 00582 } 00583 00584 static uint64_t GetOptimizationFlags(const Value *V) { 00585 uint64_t Flags = 0; 00586 00587 if (const OverflowingBinaryOperator *OBO = 00588 dyn_cast<OverflowingBinaryOperator>(V)) { 00589 if (OBO->hasNoSignedWrap()) 00590 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 00591 if (OBO->hasNoUnsignedWrap()) 00592 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 00593 } else if (const PossiblyExactOperator *PEO = 00594 dyn_cast<PossiblyExactOperator>(V)) { 00595 if (PEO->isExact()) 00596 Flags |= 1 << bitc::PEO_EXACT; 00597 } else if (const FPMathOperator *FPMO = 00598 dyn_cast<const FPMathOperator>(V)) { 00599 if (FPMO->hasUnsafeAlgebra()) 00600 Flags |= FastMathFlags::UnsafeAlgebra; 00601 if (FPMO->hasNoNaNs()) 00602 Flags |= FastMathFlags::NoNaNs; 00603 if (FPMO->hasNoInfs()) 00604 Flags |= FastMathFlags::NoInfs; 00605 if (FPMO->hasNoSignedZeros()) 00606 Flags |= FastMathFlags::NoSignedZeros; 00607 if (FPMO->hasAllowReciprocal()) 00608 Flags |= FastMathFlags::AllowReciprocal; 00609 } 00610 00611 return Flags; 00612 } 00613 00614 static void WriteMDNode(const MDNode *N, 00615 const ValueEnumerator &VE, 00616 BitstreamWriter &Stream, 00617 SmallVector<uint64_t, 64> &Record) { 00618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 00619 if (N->getOperand(i)) { 00620 Record.push_back(VE.getTypeID(N->getOperand(i)->getType())); 00621 Record.push_back(VE.getValueID(N->getOperand(i))); 00622 } else { 00623 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext()))); 00624 Record.push_back(0); 00625 } 00626 } 00627 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE : 00628 bitc::METADATA_NODE; 00629 Stream.EmitRecord(MDCode, Record, 0); 00630 Record.clear(); 00631 } 00632 00633 static void WriteModuleMetadata(const Module *M, 00634 const ValueEnumerator &VE, 00635 BitstreamWriter &Stream) { 00636 const ValueEnumerator::ValueList &Vals = VE.getMDValues(); 00637 bool StartedMetadataBlock = false; 00638 unsigned MDSAbbrev = 0; 00639 SmallVector<uint64_t, 64> Record; 00640 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 00641 00642 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) { 00643 if (!N->isFunctionLocal() || !N->getFunction()) { 00644 if (!StartedMetadataBlock) { 00645 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 00646 StartedMetadataBlock = true; 00647 } 00648 WriteMDNode(N, VE, Stream, Record); 00649 } 00650 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) { 00651 if (!StartedMetadataBlock) { 00652 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 00653 00654 // Abbrev for METADATA_STRING. 00655 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 00656 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING)); 00657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 00659 MDSAbbrev = Stream.EmitAbbrev(Abbv); 00660 StartedMetadataBlock = true; 00661 } 00662 00663 // Code: [strchar x N] 00664 Record.append(MDS->begin(), MDS->end()); 00665 00666 // Emit the finished record. 00667 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev); 00668 Record.clear(); 00669 } 00670 } 00671 00672 // Write named metadata. 00673 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 00674 E = M->named_metadata_end(); I != E; ++I) { 00675 const NamedMDNode *NMD = I; 00676 if (!StartedMetadataBlock) { 00677 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 00678 StartedMetadataBlock = true; 00679 } 00680 00681 // Write name. 00682 StringRef Str = NMD->getName(); 00683 for (unsigned i = 0, e = Str.size(); i != e; ++i) 00684 Record.push_back(Str[i]); 00685 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/); 00686 Record.clear(); 00687 00688 // Write named metadata operands. 00689 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) 00690 Record.push_back(VE.getValueID(NMD->getOperand(i))); 00691 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 00692 Record.clear(); 00693 } 00694 00695 if (StartedMetadataBlock) 00696 Stream.ExitBlock(); 00697 } 00698 00699 static void WriteFunctionLocalMetadata(const Function &F, 00700 const ValueEnumerator &VE, 00701 BitstreamWriter &Stream) { 00702 bool StartedMetadataBlock = false; 00703 SmallVector<uint64_t, 64> Record; 00704 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues(); 00705 for (unsigned i = 0, e = Vals.size(); i != e; ++i) 00706 if (const MDNode *N = Vals[i]) 00707 if (N->isFunctionLocal() && N->getFunction() == &F) { 00708 if (!StartedMetadataBlock) { 00709 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 00710 StartedMetadataBlock = true; 00711 } 00712 WriteMDNode(N, VE, Stream, Record); 00713 } 00714 00715 if (StartedMetadataBlock) 00716 Stream.ExitBlock(); 00717 } 00718 00719 static void WriteMetadataAttachment(const Function &F, 00720 const ValueEnumerator &VE, 00721 BitstreamWriter &Stream) { 00722 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 00723 00724 SmallVector<uint64_t, 64> Record; 00725 00726 // Write metadata attachments 00727 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 00728 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs; 00729 00730 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 00731 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 00732 I != E; ++I) { 00733 MDs.clear(); 00734 I->getAllMetadataOtherThanDebugLoc(MDs); 00735 00736 // If no metadata, ignore instruction. 00737 if (MDs.empty()) continue; 00738 00739 Record.push_back(VE.getInstructionID(I)); 00740 00741 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 00742 Record.push_back(MDs[i].first); 00743 Record.push_back(VE.getValueID(MDs[i].second)); 00744 } 00745 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 00746 Record.clear(); 00747 } 00748 00749 Stream.ExitBlock(); 00750 } 00751 00752 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { 00753 SmallVector<uint64_t, 64> Record; 00754 00755 // Write metadata kinds 00756 // METADATA_KIND - [n x [id, name]] 00757 SmallVector<StringRef, 8> Names; 00758 M->getMDKindNames(Names); 00759 00760 if (Names.empty()) return; 00761 00762 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 00763 00764 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 00765 Record.push_back(MDKindID); 00766 StringRef KName = Names[MDKindID]; 00767 Record.append(KName.begin(), KName.end()); 00768 00769 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 00770 Record.clear(); 00771 } 00772 00773 Stream.ExitBlock(); 00774 } 00775 00776 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 00777 if ((int64_t)V >= 0) 00778 Vals.push_back(V << 1); 00779 else 00780 Vals.push_back((-V << 1) | 1); 00781 } 00782 00783 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals, 00784 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val, 00785 bool EmitSizeForWideNumbers = false 00786 ) { 00787 if (Val.getBitWidth() <= 64) { 00788 uint64_t V = Val.getSExtValue(); 00789 emitSignedInt64(Vals, V); 00790 Code = bitc::CST_CODE_INTEGER; 00791 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 00792 } else { 00793 // Wide integers, > 64 bits in size. 00794 // We have an arbitrary precision integer value to write whose 00795 // bit width is > 64. However, in canonical unsigned integer 00796 // format it is likely that the high bits are going to be zero. 00797 // So, we only write the number of active words. 00798 unsigned NWords = Val.getActiveWords(); 00799 00800 if (EmitSizeForWideNumbers) 00801 Vals.push_back(NWords); 00802 00803 const uint64_t *RawWords = Val.getRawData(); 00804 for (unsigned i = 0; i != NWords; ++i) { 00805 emitSignedInt64(Vals, RawWords[i]); 00806 } 00807 Code = bitc::CST_CODE_WIDE_INTEGER; 00808 } 00809 } 00810 00811 static void WriteConstants(unsigned FirstVal, unsigned LastVal, 00812 const ValueEnumerator &VE, 00813 BitstreamWriter &Stream, bool isGlobal) { 00814 if (FirstVal == LastVal) return; 00815 00816 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 00817 00818 unsigned AggregateAbbrev = 0; 00819 unsigned String8Abbrev = 0; 00820 unsigned CString7Abbrev = 0; 00821 unsigned CString6Abbrev = 0; 00822 // If this is a constant pool for the module, emit module-specific abbrevs. 00823 if (isGlobal) { 00824 // Abbrev for CST_CODE_AGGREGATE. 00825 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 00826 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 00827 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 00829 AggregateAbbrev = Stream.EmitAbbrev(Abbv); 00830 00831 // Abbrev for CST_CODE_STRING. 00832 Abbv = new BitCodeAbbrev(); 00833 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 00834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00835 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 00836 String8Abbrev = Stream.EmitAbbrev(Abbv); 00837 // Abbrev for CST_CODE_CSTRING. 00838 Abbv = new BitCodeAbbrev(); 00839 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 00840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 00842 CString7Abbrev = Stream.EmitAbbrev(Abbv); 00843 // Abbrev for CST_CODE_CSTRING. 00844 Abbv = new BitCodeAbbrev(); 00845 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 00846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 00847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 00848 CString6Abbrev = Stream.EmitAbbrev(Abbv); 00849 } 00850 00851 SmallVector<uint64_t, 64> Record; 00852 00853 const ValueEnumerator::ValueList &Vals = VE.getValues(); 00854 Type *LastTy = 0; 00855 for (unsigned i = FirstVal; i != LastVal; ++i) { 00856 const Value *V = Vals[i].first; 00857 // If we need to switch types, do so now. 00858 if (V->getType() != LastTy) { 00859 LastTy = V->getType(); 00860 Record.push_back(VE.getTypeID(LastTy)); 00861 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 00862 CONSTANTS_SETTYPE_ABBREV); 00863 Record.clear(); 00864 } 00865 00866 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 00867 Record.push_back(unsigned(IA->hasSideEffects()) | 00868 unsigned(IA->isAlignStack()) << 1 | 00869 unsigned(IA->getDialect()&1) << 2); 00870 00871 // Add the asm string. 00872 const std::string &AsmStr = IA->getAsmString(); 00873 Record.push_back(AsmStr.size()); 00874 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i) 00875 Record.push_back(AsmStr[i]); 00876 00877 // Add the constraint string. 00878 const std::string &ConstraintStr = IA->getConstraintString(); 00879 Record.push_back(ConstraintStr.size()); 00880 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i) 00881 Record.push_back(ConstraintStr[i]); 00882 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 00883 Record.clear(); 00884 continue; 00885 } 00886 const Constant *C = cast<Constant>(V); 00887 unsigned Code = -1U; 00888 unsigned AbbrevToUse = 0; 00889 if (C->isNullValue()) { 00890 Code = bitc::CST_CODE_NULL; 00891 } else if (isa<UndefValue>(C)) { 00892 Code = bitc::CST_CODE_UNDEF; 00893 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 00894 EmitAPInt(Record, Code, AbbrevToUse, IV->getValue()); 00895 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 00896 Code = bitc::CST_CODE_FLOAT; 00897 Type *Ty = CFP->getType(); 00898 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 00899 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 00900 } else if (Ty->isX86_FP80Ty()) { 00901 // api needed to prevent premature destruction 00902 // bits are not in the same order as a normal i80 APInt, compensate. 00903 APInt api = CFP->getValueAPF().bitcastToAPInt(); 00904 const uint64_t *p = api.getRawData(); 00905 Record.push_back((p[1] << 48) | (p[0] >> 16)); 00906 Record.push_back(p[0] & 0xffffLL); 00907 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 00908 APInt api = CFP->getValueAPF().bitcastToAPInt(); 00909 const uint64_t *p = api.getRawData(); 00910 Record.push_back(p[0]); 00911 Record.push_back(p[1]); 00912 } else { 00913 assert (0 && "Unknown FP type!"); 00914 } 00915 } else if (isa<ConstantDataSequential>(C) && 00916 cast<ConstantDataSequential>(C)->isString()) { 00917 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 00918 // Emit constant strings specially. 00919 unsigned NumElts = Str->getNumElements(); 00920 // If this is a null-terminated string, use the denser CSTRING encoding. 00921 if (Str->isCString()) { 00922 Code = bitc::CST_CODE_CSTRING; 00923 --NumElts; // Don't encode the null, which isn't allowed by char6. 00924 } else { 00925 Code = bitc::CST_CODE_STRING; 00926 AbbrevToUse = String8Abbrev; 00927 } 00928 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 00929 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 00930 for (unsigned i = 0; i != NumElts; ++i) { 00931 unsigned char V = Str->getElementAsInteger(i); 00932 Record.push_back(V); 00933 isCStr7 &= (V & 128) == 0; 00934 if (isCStrChar6) 00935 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 00936 } 00937 00938 if (isCStrChar6) 00939 AbbrevToUse = CString6Abbrev; 00940 else if (isCStr7) 00941 AbbrevToUse = CString7Abbrev; 00942 } else if (const ConstantDataSequential *CDS = 00943 dyn_cast<ConstantDataSequential>(C)) { 00944 Code = bitc::CST_CODE_DATA; 00945 Type *EltTy = CDS->getType()->getElementType(); 00946 if (isa<IntegerType>(EltTy)) { 00947 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 00948 Record.push_back(CDS->getElementAsInteger(i)); 00949 } else if (EltTy->isFloatTy()) { 00950 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 00951 union { float F; uint32_t I; }; 00952 F = CDS->getElementAsFloat(i); 00953 Record.push_back(I); 00954 } 00955 } else { 00956 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type"); 00957 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 00958 union { double F; uint64_t I; }; 00959 F = CDS->getElementAsDouble(i); 00960 Record.push_back(I); 00961 } 00962 } 00963 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) || 00964 isa<ConstantVector>(C)) { 00965 Code = bitc::CST_CODE_AGGREGATE; 00966 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) 00967 Record.push_back(VE.getValueID(C->getOperand(i))); 00968 AbbrevToUse = AggregateAbbrev; 00969 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 00970 switch (CE->getOpcode()) { 00971 default: 00972 if (Instruction::isCast(CE->getOpcode())) { 00973 Code = bitc::CST_CODE_CE_CAST; 00974 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 00975 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 00976 Record.push_back(VE.getValueID(C->getOperand(0))); 00977 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 00978 } else { 00979 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 00980 Code = bitc::CST_CODE_CE_BINOP; 00981 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 00982 Record.push_back(VE.getValueID(C->getOperand(0))); 00983 Record.push_back(VE.getValueID(C->getOperand(1))); 00984 uint64_t Flags = GetOptimizationFlags(CE); 00985 if (Flags != 0) 00986 Record.push_back(Flags); 00987 } 00988 break; 00989 case Instruction::GetElementPtr: 00990 Code = bitc::CST_CODE_CE_GEP; 00991 if (cast<GEPOperator>(C)->isInBounds()) 00992 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 00993 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 00994 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 00995 Record.push_back(VE.getValueID(C->getOperand(i))); 00996 } 00997 break; 00998 case Instruction::Select: 00999 Code = bitc::CST_CODE_CE_SELECT; 01000 Record.push_back(VE.getValueID(C->getOperand(0))); 01001 Record.push_back(VE.getValueID(C->getOperand(1))); 01002 Record.push_back(VE.getValueID(C->getOperand(2))); 01003 break; 01004 case Instruction::ExtractElement: 01005 Code = bitc::CST_CODE_CE_EXTRACTELT; 01006 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 01007 Record.push_back(VE.getValueID(C->getOperand(0))); 01008 Record.push_back(VE.getValueID(C->getOperand(1))); 01009 break; 01010 case Instruction::InsertElement: 01011 Code = bitc::CST_CODE_CE_INSERTELT; 01012 Record.push_back(VE.getValueID(C->getOperand(0))); 01013 Record.push_back(VE.getValueID(C->getOperand(1))); 01014 Record.push_back(VE.getValueID(C->getOperand(2))); 01015 break; 01016 case Instruction::ShuffleVector: 01017 // If the return type and argument types are the same, this is a 01018 // standard shufflevector instruction. If the types are different, 01019 // then the shuffle is widening or truncating the input vectors, and 01020 // the argument type must also be encoded. 01021 if (C->getType() == C->getOperand(0)->getType()) { 01022 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 01023 } else { 01024 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 01025 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 01026 } 01027 Record.push_back(VE.getValueID(C->getOperand(0))); 01028 Record.push_back(VE.getValueID(C->getOperand(1))); 01029 Record.push_back(VE.getValueID(C->getOperand(2))); 01030 break; 01031 case Instruction::ICmp: 01032 case Instruction::FCmp: 01033 Code = bitc::CST_CODE_CE_CMP; 01034 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 01035 Record.push_back(VE.getValueID(C->getOperand(0))); 01036 Record.push_back(VE.getValueID(C->getOperand(1))); 01037 Record.push_back(CE->getPredicate()); 01038 break; 01039 } 01040 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 01041 Code = bitc::CST_CODE_BLOCKADDRESS; 01042 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 01043 Record.push_back(VE.getValueID(BA->getFunction())); 01044 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 01045 } else { 01046 #ifndef NDEBUG 01047 C->dump(); 01048 #endif 01049 llvm_unreachable("Unknown constant!"); 01050 } 01051 Stream.EmitRecord(Code, Record, AbbrevToUse); 01052 Record.clear(); 01053 } 01054 01055 Stream.ExitBlock(); 01056 } 01057 01058 static void WriteModuleConstants(const ValueEnumerator &VE, 01059 BitstreamWriter &Stream) { 01060 const ValueEnumerator::ValueList &Vals = VE.getValues(); 01061 01062 // Find the first constant to emit, which is the first non-globalvalue value. 01063 // We know globalvalues have been emitted by WriteModuleInfo. 01064 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 01065 if (!isa<GlobalValue>(Vals[i].first)) { 01066 WriteConstants(i, Vals.size(), VE, Stream, true); 01067 return; 01068 } 01069 } 01070 } 01071 01072 /// PushValueAndType - The file has to encode both the value and type id for 01073 /// many values, because we need to know what type to create for forward 01074 /// references. However, most operands are not forward references, so this type 01075 /// field is not needed. 01076 /// 01077 /// This function adds V's value ID to Vals. If the value ID is higher than the 01078 /// instruction ID, then it is a forward reference, and it also includes the 01079 /// type ID. The value ID that is written is encoded relative to the InstID. 01080 static bool PushValueAndType(const Value *V, unsigned InstID, 01081 SmallVector<unsigned, 64> &Vals, 01082 ValueEnumerator &VE) { 01083 unsigned ValID = VE.getValueID(V); 01084 // Make encoding relative to the InstID. 01085 Vals.push_back(InstID - ValID); 01086 if (ValID >= InstID) { 01087 Vals.push_back(VE.getTypeID(V->getType())); 01088 return true; 01089 } 01090 return false; 01091 } 01092 01093 /// pushValue - Like PushValueAndType, but where the type of the value is 01094 /// omitted (perhaps it was already encoded in an earlier operand). 01095 static void pushValue(const Value *V, unsigned InstID, 01096 SmallVector<unsigned, 64> &Vals, 01097 ValueEnumerator &VE) { 01098 unsigned ValID = VE.getValueID(V); 01099 Vals.push_back(InstID - ValID); 01100 } 01101 01102 static void pushValue64(const Value *V, unsigned InstID, 01103 SmallVector<uint64_t, 128> &Vals, 01104 ValueEnumerator &VE) { 01105 uint64_t ValID = VE.getValueID(V); 01106 Vals.push_back(InstID - ValID); 01107 } 01108 01109 static void pushValueSigned(const Value *V, unsigned InstID, 01110 SmallVector<uint64_t, 128> &Vals, 01111 ValueEnumerator &VE) { 01112 unsigned ValID = VE.getValueID(V); 01113 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 01114 emitSignedInt64(Vals, diff); 01115 } 01116 01117 /// WriteInstruction - Emit an instruction to the specified stream. 01118 static void WriteInstruction(const Instruction &I, unsigned InstID, 01119 ValueEnumerator &VE, BitstreamWriter &Stream, 01120 SmallVector<unsigned, 64> &Vals) { 01121 unsigned Code = 0; 01122 unsigned AbbrevToUse = 0; 01123 VE.setInstructionID(&I); 01124 switch (I.getOpcode()) { 01125 default: 01126 if (Instruction::isCast(I.getOpcode())) { 01127 Code = bitc::FUNC_CODE_INST_CAST; 01128 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 01129 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 01130 Vals.push_back(VE.getTypeID(I.getType())); 01131 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 01132 } else { 01133 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 01134 Code = bitc::FUNC_CODE_INST_BINOP; 01135 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 01136 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 01137 pushValue(I.getOperand(1), InstID, Vals, VE); 01138 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 01139 uint64_t Flags = GetOptimizationFlags(&I); 01140 if (Flags != 0) { 01141 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 01142 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 01143 Vals.push_back(Flags); 01144 } 01145 } 01146 break; 01147 01148 case Instruction::GetElementPtr: 01149 Code = bitc::FUNC_CODE_INST_GEP; 01150 if (cast<GEPOperator>(&I)->isInBounds()) 01151 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP; 01152 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 01153 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 01154 break; 01155 case Instruction::ExtractValue: { 01156 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 01157 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01158 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 01159 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 01160 Vals.push_back(*i); 01161 break; 01162 } 01163 case Instruction::InsertValue: { 01164 Code = bitc::FUNC_CODE_INST_INSERTVAL; 01165 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01166 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 01167 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 01168 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 01169 Vals.push_back(*i); 01170 break; 01171 } 01172 case Instruction::Select: 01173 Code = bitc::FUNC_CODE_INST_VSELECT; 01174 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 01175 pushValue(I.getOperand(2), InstID, Vals, VE); 01176 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01177 break; 01178 case Instruction::ExtractElement: 01179 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 01180 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01181 pushValue(I.getOperand(1), InstID, Vals, VE); 01182 break; 01183 case Instruction::InsertElement: 01184 Code = bitc::FUNC_CODE_INST_INSERTELT; 01185 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01186 pushValue(I.getOperand(1), InstID, Vals, VE); 01187 pushValue(I.getOperand(2), InstID, Vals, VE); 01188 break; 01189 case Instruction::ShuffleVector: 01190 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 01191 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01192 pushValue(I.getOperand(1), InstID, Vals, VE); 01193 pushValue(I.getOperand(2), InstID, Vals, VE); 01194 break; 01195 case Instruction::ICmp: 01196 case Instruction::FCmp: 01197 // compare returning Int1Ty or vector of Int1Ty 01198 Code = bitc::FUNC_CODE_INST_CMP2; 01199 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01200 pushValue(I.getOperand(1), InstID, Vals, VE); 01201 Vals.push_back(cast<CmpInst>(I).getPredicate()); 01202 break; 01203 01204 case Instruction::Ret: 01205 { 01206 Code = bitc::FUNC_CODE_INST_RET; 01207 unsigned NumOperands = I.getNumOperands(); 01208 if (NumOperands == 0) 01209 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 01210 else if (NumOperands == 1) { 01211 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 01212 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 01213 } else { 01214 for (unsigned i = 0, e = NumOperands; i != e; ++i) 01215 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 01216 } 01217 } 01218 break; 01219 case Instruction::Br: 01220 { 01221 Code = bitc::FUNC_CODE_INST_BR; 01222 const BranchInst &II = cast<BranchInst>(I); 01223 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 01224 if (II.isConditional()) { 01225 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 01226 pushValue(II.getCondition(), InstID, Vals, VE); 01227 } 01228 } 01229 break; 01230 case Instruction::Switch: 01231 { 01232 // Redefine Vals, since here we need to use 64 bit values 01233 // explicitly to store large APInt numbers. 01234 SmallVector<uint64_t, 128> Vals64; 01235 01236 Code = bitc::FUNC_CODE_INST_SWITCH; 01237 const SwitchInst &SI = cast<SwitchInst>(I); 01238 01239 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16); 01240 Vals64.push_back(SwitchRecordHeader); 01241 01242 Vals64.push_back(VE.getTypeID(SI.getCondition()->getType())); 01243 pushValue64(SI.getCondition(), InstID, Vals64, VE); 01244 Vals64.push_back(VE.getValueID(SI.getDefaultDest())); 01245 Vals64.push_back(SI.getNumCases()); 01246 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end(); 01247 i != e; ++i) { 01248 const IntegersSubset& CaseRanges = i.getCaseValueEx(); 01249 unsigned Code, Abbrev; // will unused. 01250 01251 if (CaseRanges.isSingleNumber()) { 01252 Vals64.push_back(1/*NumItems = 1*/); 01253 Vals64.push_back(true/*IsSingleNumber = true*/); 01254 EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true); 01255 } else { 01256 01257 Vals64.push_back(CaseRanges.getNumItems()); 01258 01259 if (CaseRanges.isSingleNumbersOnly()) { 01260 for (unsigned ri = 0, rn = CaseRanges.getNumItems(); 01261 ri != rn; ++ri) { 01262 01263 Vals64.push_back(true/*IsSingleNumber = true*/); 01264 01265 EmitAPInt(Vals64, Code, Abbrev, 01266 CaseRanges.getSingleNumber(ri), true); 01267 } 01268 } else 01269 for (unsigned ri = 0, rn = CaseRanges.getNumItems(); 01270 ri != rn; ++ri) { 01271 IntegersSubset::Range r = CaseRanges.getItem(ri); 01272 bool IsSingleNumber = CaseRanges.isSingleNumber(ri); 01273 01274 Vals64.push_back(IsSingleNumber); 01275 01276 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true); 01277 if (!IsSingleNumber) 01278 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true); 01279 } 01280 } 01281 Vals64.push_back(VE.getValueID(i.getCaseSuccessor())); 01282 } 01283 01284 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 01285 01286 // Also do expected action - clear external Vals collection: 01287 Vals.clear(); 01288 return; 01289 } 01290 break; 01291 case Instruction::IndirectBr: 01292 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 01293 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 01294 // Encode the address operand as relative, but not the basic blocks. 01295 pushValue(I.getOperand(0), InstID, Vals, VE); 01296 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 01297 Vals.push_back(VE.getValueID(I.getOperand(i))); 01298 break; 01299 01300 case Instruction::Invoke: { 01301 const InvokeInst *II = cast<InvokeInst>(&I); 01302 const Value *Callee(II->getCalledValue()); 01303 PointerType *PTy = cast<PointerType>(Callee->getType()); 01304 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 01305 Code = bitc::FUNC_CODE_INST_INVOKE; 01306 01307 Vals.push_back(VE.getAttributeID(II->getAttributes())); 01308 Vals.push_back(II->getCallingConv()); 01309 Vals.push_back(VE.getValueID(II->getNormalDest())); 01310 Vals.push_back(VE.getValueID(II->getUnwindDest())); 01311 PushValueAndType(Callee, InstID, Vals, VE); 01312 01313 // Emit value #'s for the fixed parameters. 01314 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 01315 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param. 01316 01317 // Emit type/value pairs for varargs params. 01318 if (FTy->isVarArg()) { 01319 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 01320 i != e; ++i) 01321 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg 01322 } 01323 break; 01324 } 01325 case Instruction::Resume: 01326 Code = bitc::FUNC_CODE_INST_RESUME; 01327 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01328 break; 01329 case Instruction::Unreachable: 01330 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 01331 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 01332 break; 01333 01334 case Instruction::PHI: { 01335 const PHINode &PN = cast<PHINode>(I); 01336 Code = bitc::FUNC_CODE_INST_PHI; 01337 // With the newer instruction encoding, forward references could give 01338 // negative valued IDs. This is most common for PHIs, so we use 01339 // signed VBRs. 01340 SmallVector<uint64_t, 128> Vals64; 01341 Vals64.push_back(VE.getTypeID(PN.getType())); 01342 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 01343 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE); 01344 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 01345 } 01346 // Emit a Vals64 vector and exit. 01347 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 01348 Vals64.clear(); 01349 return; 01350 } 01351 01352 case Instruction::LandingPad: { 01353 const LandingPadInst &LP = cast<LandingPadInst>(I); 01354 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 01355 Vals.push_back(VE.getTypeID(LP.getType())); 01356 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE); 01357 Vals.push_back(LP.isCleanup()); 01358 Vals.push_back(LP.getNumClauses()); 01359 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 01360 if (LP.isCatch(I)) 01361 Vals.push_back(LandingPadInst::Catch); 01362 else 01363 Vals.push_back(LandingPadInst::Filter); 01364 PushValueAndType(LP.getClause(I), InstID, Vals, VE); 01365 } 01366 break; 01367 } 01368 01369 case Instruction::Alloca: 01370 Code = bitc::FUNC_CODE_INST_ALLOCA; 01371 Vals.push_back(VE.getTypeID(I.getType())); 01372 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 01373 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 01374 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1); 01375 break; 01376 01377 case Instruction::Load: 01378 if (cast<LoadInst>(I).isAtomic()) { 01379 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 01380 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 01381 } else { 01382 Code = bitc::FUNC_CODE_INST_LOAD; 01383 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr 01384 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 01385 } 01386 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 01387 Vals.push_back(cast<LoadInst>(I).isVolatile()); 01388 if (cast<LoadInst>(I).isAtomic()) { 01389 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering())); 01390 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope())); 01391 } 01392 break; 01393 case Instruction::Store: 01394 if (cast<StoreInst>(I).isAtomic()) 01395 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 01396 else 01397 Code = bitc::FUNC_CODE_INST_STORE; 01398 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr 01399 pushValue(I.getOperand(0), InstID, Vals, VE); // val. 01400 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 01401 Vals.push_back(cast<StoreInst>(I).isVolatile()); 01402 if (cast<StoreInst>(I).isAtomic()) { 01403 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering())); 01404 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope())); 01405 } 01406 break; 01407 case Instruction::AtomicCmpXchg: 01408 Code = bitc::FUNC_CODE_INST_CMPXCHG; 01409 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 01410 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp. 01411 pushValue(I.getOperand(2), InstID, Vals, VE); // newval. 01412 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 01413 Vals.push_back(GetEncodedOrdering( 01414 cast<AtomicCmpXchgInst>(I).getOrdering())); 01415 Vals.push_back(GetEncodedSynchScope( 01416 cast<AtomicCmpXchgInst>(I).getSynchScope())); 01417 break; 01418 case Instruction::AtomicRMW: 01419 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 01420 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 01421 pushValue(I.getOperand(1), InstID, Vals, VE); // val. 01422 Vals.push_back(GetEncodedRMWOperation( 01423 cast<AtomicRMWInst>(I).getOperation())); 01424 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 01425 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 01426 Vals.push_back(GetEncodedSynchScope( 01427 cast<AtomicRMWInst>(I).getSynchScope())); 01428 break; 01429 case Instruction::Fence: 01430 Code = bitc::FUNC_CODE_INST_FENCE; 01431 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering())); 01432 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope())); 01433 break; 01434 case Instruction::Call: { 01435 const CallInst &CI = cast<CallInst>(I); 01436 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType()); 01437 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 01438 01439 Code = bitc::FUNC_CODE_INST_CALL; 01440 01441 Vals.push_back(VE.getAttributeID(CI.getAttributes())); 01442 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall())); 01443 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee 01444 01445 // Emit value #'s for the fixed parameters. 01446 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 01447 // Check for labels (can happen with asm labels). 01448 if (FTy->getParamType(i)->isLabelTy()) 01449 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 01450 else 01451 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param. 01452 } 01453 01454 // Emit type/value pairs for varargs params. 01455 if (FTy->isVarArg()) { 01456 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 01457 i != e; ++i) 01458 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs 01459 } 01460 break; 01461 } 01462 case Instruction::VAArg: 01463 Code = bitc::FUNC_CODE_INST_VAARG; 01464 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 01465 pushValue(I.getOperand(0), InstID, Vals, VE); // valist. 01466 Vals.push_back(VE.getTypeID(I.getType())); // restype. 01467 break; 01468 } 01469 01470 Stream.EmitRecord(Code, Vals, AbbrevToUse); 01471 Vals.clear(); 01472 } 01473 01474 // Emit names for globals/functions etc. 01475 static void WriteValueSymbolTable(const ValueSymbolTable &VST, 01476 const ValueEnumerator &VE, 01477 BitstreamWriter &Stream) { 01478 if (VST.empty()) return; 01479 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 01480 01481 // FIXME: Set up the abbrev, we know how many values there are! 01482 // FIXME: We know if the type names can use 7-bit ascii. 01483 SmallVector<unsigned, 64> NameVals; 01484 01485 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); 01486 SI != SE; ++SI) { 01487 01488 const ValueName &Name = *SI; 01489 01490 // Figure out the encoding to use for the name. 01491 bool is7Bit = true; 01492 bool isChar6 = true; 01493 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength(); 01494 C != E; ++C) { 01495 if (isChar6) 01496 isChar6 = BitCodeAbbrevOp::isChar6(*C); 01497 if ((unsigned char)*C & 128) { 01498 is7Bit = false; 01499 break; // don't bother scanning the rest. 01500 } 01501 } 01502 01503 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 01504 01505 // VST_ENTRY: [valueid, namechar x N] 01506 // VST_BBENTRY: [bbid, namechar x N] 01507 unsigned Code; 01508 if (isa<BasicBlock>(SI->getValue())) { 01509 Code = bitc::VST_CODE_BBENTRY; 01510 if (isChar6) 01511 AbbrevToUse = VST_BBENTRY_6_ABBREV; 01512 } else { 01513 Code = bitc::VST_CODE_ENTRY; 01514 if (isChar6) 01515 AbbrevToUse = VST_ENTRY_6_ABBREV; 01516 else if (is7Bit) 01517 AbbrevToUse = VST_ENTRY_7_ABBREV; 01518 } 01519 01520 NameVals.push_back(VE.getValueID(SI->getValue())); 01521 for (const char *P = Name.getKeyData(), 01522 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P) 01523 NameVals.push_back((unsigned char)*P); 01524 01525 // Emit the finished record. 01526 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 01527 NameVals.clear(); 01528 } 01529 Stream.ExitBlock(); 01530 } 01531 01532 /// WriteFunction - Emit a function body to the module stream. 01533 static void WriteFunction(const Function &F, ValueEnumerator &VE, 01534 BitstreamWriter &Stream) { 01535 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 01536 VE.incorporateFunction(F); 01537 01538 SmallVector<unsigned, 64> Vals; 01539 01540 // Emit the number of basic blocks, so the reader can create them ahead of 01541 // time. 01542 Vals.push_back(VE.getBasicBlocks().size()); 01543 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 01544 Vals.clear(); 01545 01546 // If there are function-local constants, emit them now. 01547 unsigned CstStart, CstEnd; 01548 VE.getFunctionConstantRange(CstStart, CstEnd); 01549 WriteConstants(CstStart, CstEnd, VE, Stream, false); 01550 01551 // If there is function-local metadata, emit it now. 01552 WriteFunctionLocalMetadata(F, VE, Stream); 01553 01554 // Keep a running idea of what the instruction ID is. 01555 unsigned InstID = CstEnd; 01556 01557 bool NeedsMetadataAttachment = false; 01558 01559 DebugLoc LastDL; 01560 01561 // Finally, emit all the instructions, in order. 01562 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 01563 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 01564 I != E; ++I) { 01565 WriteInstruction(*I, InstID, VE, Stream, Vals); 01566 01567 if (!I->getType()->isVoidTy()) 01568 ++InstID; 01569 01570 // If the instruction has metadata, write a metadata attachment later. 01571 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 01572 01573 // If the instruction has a debug location, emit it. 01574 DebugLoc DL = I->getDebugLoc(); 01575 if (DL.isUnknown()) { 01576 // nothing todo. 01577 } else if (DL == LastDL) { 01578 // Just repeat the same debug loc as last time. 01579 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 01580 } else { 01581 MDNode *Scope, *IA; 01582 DL.getScopeAndInlinedAt(Scope, IA, I->getContext()); 01583 01584 Vals.push_back(DL.getLine()); 01585 Vals.push_back(DL.getCol()); 01586 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0); 01587 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0); 01588 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 01589 Vals.clear(); 01590 01591 LastDL = DL; 01592 } 01593 } 01594 01595 // Emit names for all the instructions etc. 01596 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 01597 01598 if (NeedsMetadataAttachment) 01599 WriteMetadataAttachment(F, VE, Stream); 01600 VE.purgeFunction(); 01601 Stream.ExitBlock(); 01602 } 01603 01604 // Emit blockinfo, which defines the standard abbreviations etc. 01605 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { 01606 // We only want to emit block info records for blocks that have multiple 01607 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 01608 // Other blocks can define their abbrevs inline. 01609 Stream.EnterBlockInfoBlock(2); 01610 01611 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. 01612 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 01614 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 01615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 01616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 01617 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 01618 Abbv) != VST_ENTRY_8_ABBREV) 01619 llvm_unreachable("Unexpected abbrev ordering!"); 01620 } 01621 01622 { // 7-bit fixed width VST_ENTRY strings. 01623 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01624 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 01625 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 01626 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 01627 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 01628 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 01629 Abbv) != VST_ENTRY_7_ABBREV) 01630 llvm_unreachable("Unexpected abbrev ordering!"); 01631 } 01632 { // 6-bit char6 VST_ENTRY strings. 01633 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01634 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 01635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 01636 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 01637 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 01638 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 01639 Abbv) != VST_ENTRY_6_ABBREV) 01640 llvm_unreachable("Unexpected abbrev ordering!"); 01641 } 01642 { // 6-bit char6 VST_BBENTRY strings. 01643 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01644 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 01645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 01646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 01647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 01648 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 01649 Abbv) != VST_BBENTRY_6_ABBREV) 01650 llvm_unreachable("Unexpected abbrev ordering!"); 01651 } 01652 01653 01654 01655 { // SETTYPE abbrev for CONSTANTS_BLOCK. 01656 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01657 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 01658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 01659 Log2_32_Ceil(VE.getTypes().size()+1))); 01660 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 01661 Abbv) != CONSTANTS_SETTYPE_ABBREV) 01662 llvm_unreachable("Unexpected abbrev ordering!"); 01663 } 01664 01665 { // INTEGER abbrev for CONSTANTS_BLOCK. 01666 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01667 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 01668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 01669 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 01670 Abbv) != CONSTANTS_INTEGER_ABBREV) 01671 llvm_unreachable("Unexpected abbrev ordering!"); 01672 } 01673 01674 { // CE_CAST abbrev for CONSTANTS_BLOCK. 01675 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01676 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 01677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 01678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 01679 Log2_32_Ceil(VE.getTypes().size()+1))); 01680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 01681 01682 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 01683 Abbv) != CONSTANTS_CE_CAST_Abbrev) 01684 llvm_unreachable("Unexpected abbrev ordering!"); 01685 } 01686 { // NULL abbrev for CONSTANTS_BLOCK. 01687 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01688 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 01689 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 01690 Abbv) != CONSTANTS_NULL_Abbrev) 01691 llvm_unreachable("Unexpected abbrev ordering!"); 01692 } 01693 01694 // FIXME: This should only use space for first class types! 01695 01696 { // INST_LOAD abbrev for FUNCTION_BLOCK. 01697 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01698 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 01699 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 01700 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 01701 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 01702 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 01703 Abbv) != FUNCTION_INST_LOAD_ABBREV) 01704 llvm_unreachable("Unexpected abbrev ordering!"); 01705 } 01706 { // INST_BINOP abbrev for FUNCTION_BLOCK. 01707 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01708 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 01709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 01710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 01711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 01712 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 01713 Abbv) != FUNCTION_INST_BINOP_ABBREV) 01714 llvm_unreachable("Unexpected abbrev ordering!"); 01715 } 01716 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 01717 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01718 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 01719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 01720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 01721 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 01722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 01723 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 01724 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV) 01725 llvm_unreachable("Unexpected abbrev ordering!"); 01726 } 01727 { // INST_CAST abbrev for FUNCTION_BLOCK. 01728 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01729 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 01730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 01731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 01732 Log2_32_Ceil(VE.getTypes().size()+1))); 01733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 01734 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 01735 Abbv) != FUNCTION_INST_CAST_ABBREV) 01736 llvm_unreachable("Unexpected abbrev ordering!"); 01737 } 01738 01739 { // INST_RET abbrev for FUNCTION_BLOCK. 01740 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01741 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 01742 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 01743 Abbv) != FUNCTION_INST_RET_VOID_ABBREV) 01744 llvm_unreachable("Unexpected abbrev ordering!"); 01745 } 01746 { // INST_RET abbrev for FUNCTION_BLOCK. 01747 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01748 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 01749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 01750 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 01751 Abbv) != FUNCTION_INST_RET_VAL_ABBREV) 01752 llvm_unreachable("Unexpected abbrev ordering!"); 01753 } 01754 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 01755 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 01756 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 01757 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 01758 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV) 01759 llvm_unreachable("Unexpected abbrev ordering!"); 01760 } 01761 01762 Stream.ExitBlock(); 01763 } 01764 01765 // Sort the Users based on the order in which the reader parses the bitcode 01766 // file. 01767 static bool bitcodereader_order(const User *lhs, const User *rhs) { 01768 // TODO: Implement. 01769 return true; 01770 } 01771 01772 static void WriteUseList(const Value *V, const ValueEnumerator &VE, 01773 BitstreamWriter &Stream) { 01774 01775 // One or zero uses can't get out of order. 01776 if (V->use_empty() || V->hasNUses(1)) 01777 return; 01778 01779 // Make a copy of the in-memory use-list for sorting. 01780 unsigned UseListSize = std::distance(V->use_begin(), V->use_end()); 01781 SmallVector<const User*, 8> UseList; 01782 UseList.reserve(UseListSize); 01783 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end(); 01784 I != E; ++I) { 01785 const User *U = *I; 01786 UseList.push_back(U); 01787 } 01788 01789 // Sort the copy based on the order read by the BitcodeReader. 01790 std::sort(UseList.begin(), UseList.end(), bitcodereader_order); 01791 01792 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the 01793 // sorted list (i.e., the expected BitcodeReader in-memory use-list). 01794 01795 // TODO: Emit the USELIST_CODE_ENTRYs. 01796 } 01797 01798 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE, 01799 BitstreamWriter &Stream) { 01800 VE.incorporateFunction(*F); 01801 01802 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 01803 AI != AE; ++AI) 01804 WriteUseList(AI, VE, Stream); 01805 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE; 01806 ++BB) { 01807 WriteUseList(BB, VE, Stream); 01808 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE; 01809 ++II) { 01810 WriteUseList(II, VE, Stream); 01811 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end(); 01812 OI != E; ++OI) { 01813 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) || 01814 isa<InlineAsm>(*OI)) 01815 WriteUseList(*OI, VE, Stream); 01816 } 01817 } 01818 } 01819 VE.purgeFunction(); 01820 } 01821 01822 // Emit use-lists. 01823 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE, 01824 BitstreamWriter &Stream) { 01825 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 01826 01827 // XXX: this modifies the module, but in a way that should never change the 01828 // behavior of any pass or codegen in LLVM. The problem is that GVs may 01829 // contain entries in the use_list that do not exist in the Module and are 01830 // not stored in the .bc file. 01831 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 01832 I != E; ++I) 01833 I->removeDeadConstantUsers(); 01834 01835 // Write the global variables. 01836 for (Module::const_global_iterator GI = M->global_begin(), 01837 GE = M->global_end(); GI != GE; ++GI) { 01838 WriteUseList(GI, VE, Stream); 01839 01840 // Write the global variable initializers. 01841 if (GI->hasInitializer()) 01842 WriteUseList(GI->getInitializer(), VE, Stream); 01843 } 01844 01845 // Write the functions. 01846 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) { 01847 WriteUseList(FI, VE, Stream); 01848 if (!FI->isDeclaration()) 01849 WriteFunctionUseList(FI, VE, Stream); 01850 } 01851 01852 // Write the aliases. 01853 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end(); 01854 AI != AE; ++AI) { 01855 WriteUseList(AI, VE, Stream); 01856 WriteUseList(AI->getAliasee(), VE, Stream); 01857 } 01858 01859 Stream.ExitBlock(); 01860 } 01861 01862 /// WriteModule - Emit the specified module to the bitstream. 01863 static void WriteModule(const Module *M, BitstreamWriter &Stream) { 01864 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 01865 01866 SmallVector<unsigned, 1> Vals; 01867 unsigned CurVersion = 1; 01868 Vals.push_back(CurVersion); 01869 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 01870 01871 // Analyze the module, enumerating globals, functions, etc. 01872 ValueEnumerator VE(M); 01873 01874 // Emit blockinfo, which defines the standard abbreviations etc. 01875 WriteBlockInfo(VE, Stream); 01876 01877 // Emit information about attribute groups. 01878 WriteAttributeGroupTable(VE, Stream); 01879 01880 // Emit information about parameter attributes. 01881 WriteAttributeTable(VE, Stream); 01882 01883 // Emit information describing all of the types in the module. 01884 WriteTypeTable(VE, Stream); 01885 01886 // Emit top-level description of module, including target triple, inline asm, 01887 // descriptors for global variables, and function prototype info. 01888 WriteModuleInfo(M, VE, Stream); 01889 01890 // Emit constants. 01891 WriteModuleConstants(VE, Stream); 01892 01893 // Emit metadata. 01894 WriteModuleMetadata(M, VE, Stream); 01895 01896 // Emit metadata. 01897 WriteModuleMetadataStore(M, Stream); 01898 01899 // Emit names for globals/functions etc. 01900 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); 01901 01902 // Emit use-lists. 01903 if (EnablePreserveUseListOrdering) 01904 WriteModuleUseLists(M, VE, Stream); 01905 01906 // Emit function bodies. 01907 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) 01908 if (!F->isDeclaration()) 01909 WriteFunction(*F, VE, Stream); 01910 01911 Stream.ExitBlock(); 01912 } 01913 01914 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a 01915 /// header and trailer to make it compatible with the system archiver. To do 01916 /// this we emit the following header, and then emit a trailer that pads the 01917 /// file out to be a multiple of 16 bytes. 01918 /// 01919 /// struct bc_header { 01920 /// uint32_t Magic; // 0x0B17C0DE 01921 /// uint32_t Version; // Version, currently always 0. 01922 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 01923 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 01924 /// uint32_t CPUType; // CPU specifier. 01925 /// ... potentially more later ... 01926 /// }; 01927 enum { 01928 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size. 01929 DarwinBCHeaderSize = 5*4 01930 }; 01931 01932 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 01933 uint32_t &Position) { 01934 Buffer[Position + 0] = (unsigned char) (Value >> 0); 01935 Buffer[Position + 1] = (unsigned char) (Value >> 8); 01936 Buffer[Position + 2] = (unsigned char) (Value >> 16); 01937 Buffer[Position + 3] = (unsigned char) (Value >> 24); 01938 Position += 4; 01939 } 01940 01941 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 01942 const Triple &TT) { 01943 unsigned CPUType = ~0U; 01944 01945 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 01946 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 01947 // number from /usr/include/mach/machine.h. It is ok to reproduce the 01948 // specific constants here because they are implicitly part of the Darwin ABI. 01949 enum { 01950 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 01951 DARWIN_CPU_TYPE_X86 = 7, 01952 DARWIN_CPU_TYPE_ARM = 12, 01953 DARWIN_CPU_TYPE_POWERPC = 18 01954 }; 01955 01956 Triple::ArchType Arch = TT.getArch(); 01957 if (Arch == Triple::x86_64) 01958 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 01959 else if (Arch == Triple::x86) 01960 CPUType = DARWIN_CPU_TYPE_X86; 01961 else if (Arch == Triple::ppc) 01962 CPUType = DARWIN_CPU_TYPE_POWERPC; 01963 else if (Arch == Triple::ppc64) 01964 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 01965 else if (Arch == Triple::arm || Arch == Triple::thumb) 01966 CPUType = DARWIN_CPU_TYPE_ARM; 01967 01968 // Traditional Bitcode starts after header. 01969 assert(Buffer.size() >= DarwinBCHeaderSize && 01970 "Expected header size to be reserved"); 01971 unsigned BCOffset = DarwinBCHeaderSize; 01972 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize; 01973 01974 // Write the magic and version. 01975 unsigned Position = 0; 01976 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position); 01977 WriteInt32ToBuffer(0 , Buffer, Position); // Version. 01978 WriteInt32ToBuffer(BCOffset , Buffer, Position); 01979 WriteInt32ToBuffer(BCSize , Buffer, Position); 01980 WriteInt32ToBuffer(CPUType , Buffer, Position); 01981 01982 // If the file is not a multiple of 16 bytes, insert dummy padding. 01983 while (Buffer.size() & 15) 01984 Buffer.push_back(0); 01985 } 01986 01987 /// WriteBitcodeToFile - Write the specified module to the specified output 01988 /// stream. 01989 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) { 01990 SmallVector<char, 0> Buffer; 01991 Buffer.reserve(256*1024); 01992 01993 // If this is darwin or another generic macho target, reserve space for the 01994 // header. 01995 Triple TT(M->getTargetTriple()); 01996 if (TT.isOSDarwin()) 01997 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0); 01998 01999 // Emit the module into the buffer. 02000 { 02001 BitstreamWriter Stream(Buffer); 02002 02003 // Emit the file header. 02004 Stream.Emit((unsigned)'B', 8); 02005 Stream.Emit((unsigned)'C', 8); 02006 Stream.Emit(0x0, 4); 02007 Stream.Emit(0xC, 4); 02008 Stream.Emit(0xE, 4); 02009 Stream.Emit(0xD, 4); 02010 02011 // Emit the module. 02012 WriteModule(M, Stream); 02013 } 02014 02015 if (TT.isOSDarwin()) 02016 EmitDarwinBCHeaderAndTrailer(Buffer, TT); 02017 02018 // Write the generated bitstream to "Out". 02019 Out.write((char*)&Buffer.front(), Buffer.size()); 02020 }