1 //===- Bitcode/Writer/DXILBitcodeWriter.cpp - DXIL Bitcode Writer ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Bitcode writer implementation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "DXILBitcodeWriter.h" 14 #include "DXILValueEnumerator.h" 15 #include "PointerTypeAnalysis.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/Bitcode/BitcodeCommon.h" 18 #include "llvm/Bitcode/BitcodeReader.h" 19 #include "llvm/Bitcode/LLVMBitCodes.h" 20 #include "llvm/Bitstream/BitCodes.h" 21 #include "llvm/Bitstream/BitstreamWriter.h" 22 #include "llvm/IR/Attributes.h" 23 #include "llvm/IR/BasicBlock.h" 24 #include "llvm/IR/Comdat.h" 25 #include "llvm/IR/Constant.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DebugInfoMetadata.h" 28 #include "llvm/IR/DebugLoc.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/GlobalAlias.h" 32 #include "llvm/IR/GlobalIFunc.h" 33 #include "llvm/IR/GlobalObject.h" 34 #include "llvm/IR/GlobalValue.h" 35 #include "llvm/IR/GlobalVariable.h" 36 #include "llvm/IR/InlineAsm.h" 37 #include "llvm/IR/InstrTypes.h" 38 #include "llvm/IR/Instruction.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/LLVMContext.h" 41 #include "llvm/IR/Metadata.h" 42 #include "llvm/IR/Module.h" 43 #include "llvm/IR/ModuleSummaryIndex.h" 44 #include "llvm/IR/Operator.h" 45 #include "llvm/IR/Type.h" 46 #include "llvm/IR/UseListOrder.h" 47 #include "llvm/IR/Value.h" 48 #include "llvm/IR/ValueSymbolTable.h" 49 #include "llvm/Object/IRSymtab.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/SHA1.h" 52 53 namespace llvm { 54 namespace dxil { 55 56 // Generates an enum to use as an index in the Abbrev array of Metadata record. 57 enum MetadataAbbrev : unsigned { 58 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID, 59 #include "llvm/IR/Metadata.def" 60 LastPlusOne 61 }; 62 63 class DXILBitcodeWriter { 64 65 /// These are manifest constants used by the bitcode writer. They do not need 66 /// to be kept in sync with the reader, but need to be consistent within this 67 /// file. 68 enum { 69 // VALUE_SYMTAB_BLOCK abbrev id's. 70 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 71 VST_ENTRY_7_ABBREV, 72 VST_ENTRY_6_ABBREV, 73 VST_BBENTRY_6_ABBREV, 74 75 // CONSTANTS_BLOCK abbrev id's. 76 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 77 CONSTANTS_INTEGER_ABBREV, 78 CONSTANTS_CE_CAST_Abbrev, 79 CONSTANTS_NULL_Abbrev, 80 81 // FUNCTION_BLOCK abbrev id's. 82 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 83 FUNCTION_INST_BINOP_ABBREV, 84 FUNCTION_INST_BINOP_FLAGS_ABBREV, 85 FUNCTION_INST_CAST_ABBREV, 86 FUNCTION_INST_RET_VOID_ABBREV, 87 FUNCTION_INST_RET_VAL_ABBREV, 88 FUNCTION_INST_UNREACHABLE_ABBREV, 89 FUNCTION_INST_GEP_ABBREV, 90 }; 91 92 // Cache some types 93 Type *I8Ty; 94 Type *I8PtrTy; 95 96 /// The stream created and owned by the client. 97 BitstreamWriter &Stream; 98 99 StringTableBuilder &StrtabBuilder; 100 101 /// The Module to write to bitcode. 102 const Module &M; 103 104 /// Enumerates ids for all values in the module. 105 ValueEnumerator VE; 106 107 /// Map that holds the correspondence between GUIDs in the summary index, 108 /// that came from indirect call profiles, and a value id generated by this 109 /// class to use in the VST and summary block records. 110 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 111 112 /// Tracks the last value id recorded in the GUIDToValueMap. 113 unsigned GlobalValueId; 114 115 /// Saves the offset of the VSTOffset record that must eventually be 116 /// backpatched with the offset of the actual VST. 117 uint64_t VSTOffsetPlaceholder = 0; 118 119 /// Pointer to the buffer allocated by caller for bitcode writing. 120 const SmallVectorImpl<char> &Buffer; 121 122 /// The start bit of the identification block. 123 uint64_t BitcodeStartBit; 124 125 /// This maps values to their typed pointers 126 PointerTypeMap PointerMap; 127 128 public: 129 /// Constructs a ModuleBitcodeWriter object for the given Module, 130 /// writing to the provided \p Buffer. 131 DXILBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer, 132 StringTableBuilder &StrtabBuilder, BitstreamWriter &Stream) 133 : I8Ty(Type::getInt8Ty(M.getContext())), 134 I8PtrTy(TypedPointerType::get(I8Ty, 0)), Stream(Stream), 135 StrtabBuilder(StrtabBuilder), M(M), VE(M, I8PtrTy), Buffer(Buffer), 136 BitcodeStartBit(Stream.GetCurrentBitNo()), 137 PointerMap(PointerTypeAnalysis::run(M)) { 138 GlobalValueId = VE.getValues().size(); 139 // Enumerate the typed pointers 140 for (auto El : PointerMap) 141 VE.EnumerateType(El.second); 142 } 143 144 /// Emit the current module to the bitstream. 145 void write(); 146 147 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind); 148 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, 149 StringRef Str, unsigned AbbrevToUse); 150 static void writeIdentificationBlock(BitstreamWriter &Stream); 151 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V); 152 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A); 153 154 static unsigned getEncodedComdatSelectionKind(const Comdat &C); 155 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage); 156 static unsigned getEncodedLinkage(const GlobalValue &GV); 157 static unsigned getEncodedVisibility(const GlobalValue &GV); 158 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV); 159 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV); 160 static unsigned getEncodedCastOpcode(unsigned Opcode); 161 static unsigned getEncodedUnaryOpcode(unsigned Opcode); 162 static unsigned getEncodedBinaryOpcode(unsigned Opcode); 163 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op); 164 static unsigned getEncodedOrdering(AtomicOrdering Ordering); 165 static uint64_t getOptimizationFlags(const Value *V); 166 167 private: 168 void writeModuleVersion(); 169 void writePerModuleGlobalValueSummary(); 170 171 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 172 GlobalValueSummary *Summary, 173 unsigned ValueID, 174 unsigned FSCallsAbbrev, 175 unsigned FSCallsProfileAbbrev, 176 const Function &F); 177 void writeModuleLevelReferences(const GlobalVariable &V, 178 SmallVector<uint64_t, 64> &NameVals, 179 unsigned FSModRefsAbbrev, 180 unsigned FSModVTableRefsAbbrev); 181 182 void assignValueId(GlobalValue::GUID ValGUID) { 183 GUIDToValueIdMap[ValGUID] = ++GlobalValueId; 184 } 185 186 unsigned getValueId(GlobalValue::GUID ValGUID) { 187 const auto &VMI = GUIDToValueIdMap.find(ValGUID); 188 // Expect that any GUID value had a value Id assigned by an 189 // earlier call to assignValueId. 190 assert(VMI != GUIDToValueIdMap.end() && 191 "GUID does not have assigned value Id"); 192 return VMI->second; 193 } 194 195 // Helper to get the valueId for the type of value recorded in VI. 196 unsigned getValueId(ValueInfo VI) { 197 if (!VI.haveGVs() || !VI.getValue()) 198 return getValueId(VI.getGUID()); 199 return VE.getValueID(VI.getValue()); 200 } 201 202 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 203 204 uint64_t bitcodeStartBit() { return BitcodeStartBit; } 205 206 size_t addToStrtab(StringRef Str); 207 208 unsigned createDILocationAbbrev(); 209 unsigned createGenericDINodeAbbrev(); 210 211 void writeAttributeGroupTable(); 212 void writeAttributeTable(); 213 void writeTypeTable(); 214 void writeComdats(); 215 void writeValueSymbolTableForwardDecl(); 216 void writeModuleInfo(); 217 void writeValueAsMetadata(const ValueAsMetadata *MD, 218 SmallVectorImpl<uint64_t> &Record); 219 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record, 220 unsigned Abbrev); 221 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record, 222 unsigned &Abbrev); 223 void writeGenericDINode(const GenericDINode *N, 224 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev) { 225 llvm_unreachable("DXIL cannot contain GenericDI Nodes"); 226 } 227 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record, 228 unsigned Abbrev); 229 void writeDIGenericSubrange(const DIGenericSubrange *N, 230 SmallVectorImpl<uint64_t> &Record, 231 unsigned Abbrev) { 232 llvm_unreachable("DXIL cannot contain DIGenericSubrange Nodes"); 233 } 234 void writeDIEnumerator(const DIEnumerator *N, 235 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 236 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record, 237 unsigned Abbrev); 238 void writeDIStringType(const DIStringType *N, 239 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 240 llvm_unreachable("DXIL cannot contain DIStringType Nodes"); 241 } 242 void writeDIDerivedType(const DIDerivedType *N, 243 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 244 void writeDICompositeType(const DICompositeType *N, 245 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 246 void writeDISubroutineType(const DISubroutineType *N, 247 SmallVectorImpl<uint64_t> &Record, 248 unsigned Abbrev); 249 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record, 250 unsigned Abbrev); 251 void writeDICompileUnit(const DICompileUnit *N, 252 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 253 void writeDISubprogram(const DISubprogram *N, 254 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 255 void writeDILexicalBlock(const DILexicalBlock *N, 256 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 257 void writeDILexicalBlockFile(const DILexicalBlockFile *N, 258 SmallVectorImpl<uint64_t> &Record, 259 unsigned Abbrev); 260 void writeDICommonBlock(const DICommonBlock *N, 261 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) { 262 llvm_unreachable("DXIL cannot contain DICommonBlock Nodes"); 263 } 264 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record, 265 unsigned Abbrev); 266 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record, 267 unsigned Abbrev) { 268 llvm_unreachable("DXIL cannot contain DIMacro Nodes"); 269 } 270 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record, 271 unsigned Abbrev) { 272 llvm_unreachable("DXIL cannot contain DIMacroFile Nodes"); 273 } 274 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record, 275 unsigned Abbrev) { 276 llvm_unreachable("DXIL cannot contain DIArgList Nodes"); 277 } 278 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record, 279 unsigned Abbrev); 280 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 281 SmallVectorImpl<uint64_t> &Record, 282 unsigned Abbrev); 283 void writeDITemplateValueParameter(const DITemplateValueParameter *N, 284 SmallVectorImpl<uint64_t> &Record, 285 unsigned Abbrev); 286 void writeDIGlobalVariable(const DIGlobalVariable *N, 287 SmallVectorImpl<uint64_t> &Record, 288 unsigned Abbrev); 289 void writeDILocalVariable(const DILocalVariable *N, 290 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 291 void writeDILabel(const DILabel *N, SmallVectorImpl<uint64_t> &Record, 292 unsigned Abbrev) { 293 llvm_unreachable("DXIL cannot contain DILabel Nodes"); 294 } 295 void writeDIExpression(const DIExpression *N, 296 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 297 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N, 298 SmallVectorImpl<uint64_t> &Record, 299 unsigned Abbrev) { 300 llvm_unreachable("DXIL cannot contain GlobalVariableExpression Nodes"); 301 } 302 void writeDIObjCProperty(const DIObjCProperty *N, 303 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 304 void writeDIImportedEntity(const DIImportedEntity *N, 305 SmallVectorImpl<uint64_t> &Record, 306 unsigned Abbrev); 307 unsigned createNamedMetadataAbbrev(); 308 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record); 309 unsigned createMetadataStringsAbbrev(); 310 void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 311 SmallVectorImpl<uint64_t> &Record); 312 void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 313 SmallVectorImpl<uint64_t> &Record, 314 std::vector<unsigned> *MDAbbrevs = nullptr, 315 std::vector<uint64_t> *IndexPos = nullptr); 316 void writeModuleMetadata(); 317 void writeFunctionMetadata(const Function &F); 318 void writeFunctionMetadataAttachment(const Function &F); 319 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record, 320 const GlobalObject &GO); 321 void writeModuleMetadataKinds(); 322 void writeOperandBundleTags(); 323 void writeSyncScopeNames(); 324 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal); 325 void writeModuleConstants(); 326 bool pushValueAndType(const Value *V, unsigned InstID, 327 SmallVectorImpl<unsigned> &Vals); 328 void writeOperandBundles(const CallBase &CB, unsigned InstID); 329 void pushValue(const Value *V, unsigned InstID, 330 SmallVectorImpl<unsigned> &Vals); 331 void pushValueSigned(const Value *V, unsigned InstID, 332 SmallVectorImpl<uint64_t> &Vals); 333 void writeInstruction(const Instruction &I, unsigned InstID, 334 SmallVectorImpl<unsigned> &Vals); 335 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST); 336 void writeGlobalValueSymbolTable( 337 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 338 void writeUseList(UseListOrder &&Order); 339 void writeUseListBlock(const Function *F); 340 void writeFunction(const Function &F); 341 void writeBlockInfo(); 342 343 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { return unsigned(SSID); } 344 345 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); } 346 347 unsigned getTypeID(Type *T, const Value *V = nullptr); 348 unsigned getTypeID(Type *T, const Function *F); 349 }; 350 351 } // namespace dxil 352 } // namespace llvm 353 354 using namespace llvm; 355 using namespace llvm::dxil; 356 357 //////////////////////////////////////////////////////////////////////////////// 358 /// Begin dxil::BitcodeWriter Implementation 359 //////////////////////////////////////////////////////////////////////////////// 360 361 dxil::BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, 362 raw_fd_stream *FS) 363 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, 512)) { 364 // Emit the file header. 365 Stream->Emit((unsigned)'B', 8); 366 Stream->Emit((unsigned)'C', 8); 367 Stream->Emit(0x0, 4); 368 Stream->Emit(0xC, 4); 369 Stream->Emit(0xE, 4); 370 Stream->Emit(0xD, 4); 371 } 372 373 dxil::BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); } 374 375 /// Write the specified module to the specified output stream. 376 void dxil::WriteDXILToFile(const Module &M, raw_ostream &Out) { 377 SmallVector<char, 0> Buffer; 378 Buffer.reserve(256 * 1024); 379 380 // If this is darwin or another generic macho target, reserve space for the 381 // header. 382 Triple TT(M.getTargetTriple()); 383 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 384 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 385 386 BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out)); 387 Writer.writeModule(M); 388 Writer.writeSymtab(); 389 Writer.writeStrtab(); 390 391 // Write the generated bitstream to "Out". 392 if (!Buffer.empty()) 393 Out.write((char *)&Buffer.front(), Buffer.size()); 394 } 395 396 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) { 397 Stream->EnterSubblock(Block, 3); 398 399 auto Abbv = std::make_shared<BitCodeAbbrev>(); 400 Abbv->Add(BitCodeAbbrevOp(Record)); 401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 402 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv)); 403 404 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob); 405 406 Stream->ExitBlock(); 407 } 408 409 void BitcodeWriter::writeSymtab() { 410 assert(!WroteStrtab && !WroteSymtab); 411 412 // If any module has module-level inline asm, we will require a registered asm 413 // parser for the target so that we can create an accurate symbol table for 414 // the module. 415 for (Module *M : Mods) { 416 if (M->getModuleInlineAsm().empty()) 417 continue; 418 } 419 420 WroteSymtab = true; 421 SmallVector<char, 0> Symtab; 422 // The irsymtab::build function may be unable to create a symbol table if the 423 // module is malformed (e.g. it contains an invalid alias). Writing a symbol 424 // table is not required for correctness, but we still want to be able to 425 // write malformed modules to bitcode files, so swallow the error. 426 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) { 427 consumeError(std::move(E)); 428 return; 429 } 430 431 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB, 432 {Symtab.data(), Symtab.size()}); 433 } 434 435 void BitcodeWriter::writeStrtab() { 436 assert(!WroteStrtab); 437 438 std::vector<char> Strtab; 439 StrtabBuilder.finalizeInOrder(); 440 Strtab.resize(StrtabBuilder.getSize()); 441 StrtabBuilder.write((uint8_t *)Strtab.data()); 442 443 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, 444 {Strtab.data(), Strtab.size()}); 445 446 WroteStrtab = true; 447 } 448 449 void BitcodeWriter::copyStrtab(StringRef Strtab) { 450 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab); 451 WroteStrtab = true; 452 } 453 454 void BitcodeWriter::writeModule(const Module &M) { 455 assert(!WroteStrtab); 456 457 // The Mods vector is used by irsymtab::build, which requires non-const 458 // Modules in case it needs to materialize metadata. But the bitcode writer 459 // requires that the module is materialized, so we can cast to non-const here, 460 // after checking that it is in fact materialized. 461 assert(M.isMaterialized()); 462 Mods.push_back(const_cast<Module *>(&M)); 463 464 DXILBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream); 465 ModuleWriter.write(); 466 } 467 468 //////////////////////////////////////////////////////////////////////////////// 469 /// Begin dxil::BitcodeWriterBase Implementation 470 //////////////////////////////////////////////////////////////////////////////// 471 472 unsigned DXILBitcodeWriter::getEncodedCastOpcode(unsigned Opcode) { 473 switch (Opcode) { 474 default: 475 llvm_unreachable("Unknown cast instruction!"); 476 case Instruction::Trunc: 477 return bitc::CAST_TRUNC; 478 case Instruction::ZExt: 479 return bitc::CAST_ZEXT; 480 case Instruction::SExt: 481 return bitc::CAST_SEXT; 482 case Instruction::FPToUI: 483 return bitc::CAST_FPTOUI; 484 case Instruction::FPToSI: 485 return bitc::CAST_FPTOSI; 486 case Instruction::UIToFP: 487 return bitc::CAST_UITOFP; 488 case Instruction::SIToFP: 489 return bitc::CAST_SITOFP; 490 case Instruction::FPTrunc: 491 return bitc::CAST_FPTRUNC; 492 case Instruction::FPExt: 493 return bitc::CAST_FPEXT; 494 case Instruction::PtrToInt: 495 return bitc::CAST_PTRTOINT; 496 case Instruction::IntToPtr: 497 return bitc::CAST_INTTOPTR; 498 case Instruction::BitCast: 499 return bitc::CAST_BITCAST; 500 case Instruction::AddrSpaceCast: 501 return bitc::CAST_ADDRSPACECAST; 502 } 503 } 504 505 unsigned DXILBitcodeWriter::getEncodedUnaryOpcode(unsigned Opcode) { 506 switch (Opcode) { 507 default: 508 llvm_unreachable("Unknown binary instruction!"); 509 case Instruction::FNeg: 510 return bitc::UNOP_FNEG; 511 } 512 } 513 514 unsigned DXILBitcodeWriter::getEncodedBinaryOpcode(unsigned Opcode) { 515 switch (Opcode) { 516 default: 517 llvm_unreachable("Unknown binary instruction!"); 518 case Instruction::Add: 519 case Instruction::FAdd: 520 return bitc::BINOP_ADD; 521 case Instruction::Sub: 522 case Instruction::FSub: 523 return bitc::BINOP_SUB; 524 case Instruction::Mul: 525 case Instruction::FMul: 526 return bitc::BINOP_MUL; 527 case Instruction::UDiv: 528 return bitc::BINOP_UDIV; 529 case Instruction::FDiv: 530 case Instruction::SDiv: 531 return bitc::BINOP_SDIV; 532 case Instruction::URem: 533 return bitc::BINOP_UREM; 534 case Instruction::FRem: 535 case Instruction::SRem: 536 return bitc::BINOP_SREM; 537 case Instruction::Shl: 538 return bitc::BINOP_SHL; 539 case Instruction::LShr: 540 return bitc::BINOP_LSHR; 541 case Instruction::AShr: 542 return bitc::BINOP_ASHR; 543 case Instruction::And: 544 return bitc::BINOP_AND; 545 case Instruction::Or: 546 return bitc::BINOP_OR; 547 case Instruction::Xor: 548 return bitc::BINOP_XOR; 549 } 550 } 551 552 unsigned DXILBitcodeWriter::getTypeID(Type *T, const Value *V) { 553 if (!T->isOpaquePointerTy()) 554 return VE.getTypeID(T); 555 auto It = PointerMap.find(V); 556 if (It != PointerMap.end()) 557 return VE.getTypeID(It->second); 558 return VE.getTypeID(I8PtrTy); 559 } 560 561 unsigned DXILBitcodeWriter::getTypeID(Type *T, const Function *F) { 562 auto It = PointerMap.find(F); 563 if (It != PointerMap.end()) 564 return VE.getTypeID(It->second); 565 return VE.getTypeID(T); 566 } 567 568 unsigned DXILBitcodeWriter::getEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 569 switch (Op) { 570 default: 571 llvm_unreachable("Unknown RMW operation!"); 572 case AtomicRMWInst::Xchg: 573 return bitc::RMW_XCHG; 574 case AtomicRMWInst::Add: 575 return bitc::RMW_ADD; 576 case AtomicRMWInst::Sub: 577 return bitc::RMW_SUB; 578 case AtomicRMWInst::And: 579 return bitc::RMW_AND; 580 case AtomicRMWInst::Nand: 581 return bitc::RMW_NAND; 582 case AtomicRMWInst::Or: 583 return bitc::RMW_OR; 584 case AtomicRMWInst::Xor: 585 return bitc::RMW_XOR; 586 case AtomicRMWInst::Max: 587 return bitc::RMW_MAX; 588 case AtomicRMWInst::Min: 589 return bitc::RMW_MIN; 590 case AtomicRMWInst::UMax: 591 return bitc::RMW_UMAX; 592 case AtomicRMWInst::UMin: 593 return bitc::RMW_UMIN; 594 case AtomicRMWInst::FAdd: 595 return bitc::RMW_FADD; 596 case AtomicRMWInst::FSub: 597 return bitc::RMW_FSUB; 598 case AtomicRMWInst::FMax: 599 return bitc::RMW_FMAX; 600 case AtomicRMWInst::FMin: 601 return bitc::RMW_FMIN; 602 } 603 } 604 605 unsigned DXILBitcodeWriter::getEncodedOrdering(AtomicOrdering Ordering) { 606 switch (Ordering) { 607 case AtomicOrdering::NotAtomic: 608 return bitc::ORDERING_NOTATOMIC; 609 case AtomicOrdering::Unordered: 610 return bitc::ORDERING_UNORDERED; 611 case AtomicOrdering::Monotonic: 612 return bitc::ORDERING_MONOTONIC; 613 case AtomicOrdering::Acquire: 614 return bitc::ORDERING_ACQUIRE; 615 case AtomicOrdering::Release: 616 return bitc::ORDERING_RELEASE; 617 case AtomicOrdering::AcquireRelease: 618 return bitc::ORDERING_ACQREL; 619 case AtomicOrdering::SequentiallyConsistent: 620 return bitc::ORDERING_SEQCST; 621 } 622 llvm_unreachable("Invalid ordering"); 623 } 624 625 void DXILBitcodeWriter::writeStringRecord(BitstreamWriter &Stream, 626 unsigned Code, StringRef Str, 627 unsigned AbbrevToUse) { 628 SmallVector<unsigned, 64> Vals; 629 630 // Code: [strchar x N] 631 for (char C : Str) { 632 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C)) 633 AbbrevToUse = 0; 634 Vals.push_back(C); 635 } 636 637 // Emit the finished record. 638 Stream.EmitRecord(Code, Vals, AbbrevToUse); 639 } 640 641 uint64_t DXILBitcodeWriter::getAttrKindEncoding(Attribute::AttrKind Kind) { 642 switch (Kind) { 643 case Attribute::Alignment: 644 return bitc::ATTR_KIND_ALIGNMENT; 645 case Attribute::AlwaysInline: 646 return bitc::ATTR_KIND_ALWAYS_INLINE; 647 case Attribute::ArgMemOnly: 648 return bitc::ATTR_KIND_ARGMEMONLY; 649 case Attribute::Builtin: 650 return bitc::ATTR_KIND_BUILTIN; 651 case Attribute::ByVal: 652 return bitc::ATTR_KIND_BY_VAL; 653 case Attribute::Convergent: 654 return bitc::ATTR_KIND_CONVERGENT; 655 case Attribute::InAlloca: 656 return bitc::ATTR_KIND_IN_ALLOCA; 657 case Attribute::Cold: 658 return bitc::ATTR_KIND_COLD; 659 case Attribute::InlineHint: 660 return bitc::ATTR_KIND_INLINE_HINT; 661 case Attribute::InReg: 662 return bitc::ATTR_KIND_IN_REG; 663 case Attribute::JumpTable: 664 return bitc::ATTR_KIND_JUMP_TABLE; 665 case Attribute::MinSize: 666 return bitc::ATTR_KIND_MIN_SIZE; 667 case Attribute::Naked: 668 return bitc::ATTR_KIND_NAKED; 669 case Attribute::Nest: 670 return bitc::ATTR_KIND_NEST; 671 case Attribute::NoAlias: 672 return bitc::ATTR_KIND_NO_ALIAS; 673 case Attribute::NoBuiltin: 674 return bitc::ATTR_KIND_NO_BUILTIN; 675 case Attribute::NoCapture: 676 return bitc::ATTR_KIND_NO_CAPTURE; 677 case Attribute::NoDuplicate: 678 return bitc::ATTR_KIND_NO_DUPLICATE; 679 case Attribute::NoImplicitFloat: 680 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 681 case Attribute::NoInline: 682 return bitc::ATTR_KIND_NO_INLINE; 683 case Attribute::NonLazyBind: 684 return bitc::ATTR_KIND_NON_LAZY_BIND; 685 case Attribute::NonNull: 686 return bitc::ATTR_KIND_NON_NULL; 687 case Attribute::Dereferenceable: 688 return bitc::ATTR_KIND_DEREFERENCEABLE; 689 case Attribute::DereferenceableOrNull: 690 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 691 case Attribute::NoRedZone: 692 return bitc::ATTR_KIND_NO_RED_ZONE; 693 case Attribute::NoReturn: 694 return bitc::ATTR_KIND_NO_RETURN; 695 case Attribute::NoUnwind: 696 return bitc::ATTR_KIND_NO_UNWIND; 697 case Attribute::OptimizeForSize: 698 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 699 case Attribute::OptimizeNone: 700 return bitc::ATTR_KIND_OPTIMIZE_NONE; 701 case Attribute::ReadNone: 702 return bitc::ATTR_KIND_READ_NONE; 703 case Attribute::ReadOnly: 704 return bitc::ATTR_KIND_READ_ONLY; 705 case Attribute::Returned: 706 return bitc::ATTR_KIND_RETURNED; 707 case Attribute::ReturnsTwice: 708 return bitc::ATTR_KIND_RETURNS_TWICE; 709 case Attribute::SExt: 710 return bitc::ATTR_KIND_S_EXT; 711 case Attribute::StackAlignment: 712 return bitc::ATTR_KIND_STACK_ALIGNMENT; 713 case Attribute::StackProtect: 714 return bitc::ATTR_KIND_STACK_PROTECT; 715 case Attribute::StackProtectReq: 716 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 717 case Attribute::StackProtectStrong: 718 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 719 case Attribute::SafeStack: 720 return bitc::ATTR_KIND_SAFESTACK; 721 case Attribute::StructRet: 722 return bitc::ATTR_KIND_STRUCT_RET; 723 case Attribute::SanitizeAddress: 724 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 725 case Attribute::SanitizeThread: 726 return bitc::ATTR_KIND_SANITIZE_THREAD; 727 case Attribute::SanitizeMemory: 728 return bitc::ATTR_KIND_SANITIZE_MEMORY; 729 case Attribute::UWTable: 730 return bitc::ATTR_KIND_UW_TABLE; 731 case Attribute::ZExt: 732 return bitc::ATTR_KIND_Z_EXT; 733 case Attribute::EndAttrKinds: 734 llvm_unreachable("Can not encode end-attribute kinds marker."); 735 case Attribute::None: 736 llvm_unreachable("Can not encode none-attribute."); 737 case Attribute::EmptyKey: 738 case Attribute::TombstoneKey: 739 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey"); 740 default: 741 llvm_unreachable("Trying to encode attribute not supported by DXIL. These " 742 "should be stripped in DXILPrepare"); 743 } 744 745 llvm_unreachable("Trying to encode unknown attribute"); 746 } 747 748 void DXILBitcodeWriter::emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, 749 uint64_t V) { 750 if ((int64_t)V >= 0) 751 Vals.push_back(V << 1); 752 else 753 Vals.push_back((-V << 1) | 1); 754 } 755 756 void DXILBitcodeWriter::emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, 757 const APInt &A) { 758 // We have an arbitrary precision integer value to write whose 759 // bit width is > 64. However, in canonical unsigned integer 760 // format it is likely that the high bits are going to be zero. 761 // So, we only write the number of active words. 762 unsigned NumWords = A.getActiveWords(); 763 const uint64_t *RawData = A.getRawData(); 764 for (unsigned i = 0; i < NumWords; i++) 765 emitSignedInt64(Vals, RawData[i]); 766 } 767 768 uint64_t DXILBitcodeWriter::getOptimizationFlags(const Value *V) { 769 uint64_t Flags = 0; 770 771 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 772 if (OBO->hasNoSignedWrap()) 773 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 774 if (OBO->hasNoUnsignedWrap()) 775 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 776 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 777 if (PEO->isExact()) 778 Flags |= 1 << bitc::PEO_EXACT; 779 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 780 if (FPMO->hasAllowReassoc()) 781 Flags |= bitc::AllowReassoc; 782 if (FPMO->hasNoNaNs()) 783 Flags |= bitc::NoNaNs; 784 if (FPMO->hasNoInfs()) 785 Flags |= bitc::NoInfs; 786 if (FPMO->hasNoSignedZeros()) 787 Flags |= bitc::NoSignedZeros; 788 if (FPMO->hasAllowReciprocal()) 789 Flags |= bitc::AllowReciprocal; 790 if (FPMO->hasAllowContract()) 791 Flags |= bitc::AllowContract; 792 if (FPMO->hasApproxFunc()) 793 Flags |= bitc::ApproxFunc; 794 } 795 796 return Flags; 797 } 798 799 unsigned 800 DXILBitcodeWriter::getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 801 switch (Linkage) { 802 case GlobalValue::ExternalLinkage: 803 return 0; 804 case GlobalValue::WeakAnyLinkage: 805 return 16; 806 case GlobalValue::AppendingLinkage: 807 return 2; 808 case GlobalValue::InternalLinkage: 809 return 3; 810 case GlobalValue::LinkOnceAnyLinkage: 811 return 18; 812 case GlobalValue::ExternalWeakLinkage: 813 return 7; 814 case GlobalValue::CommonLinkage: 815 return 8; 816 case GlobalValue::PrivateLinkage: 817 return 9; 818 case GlobalValue::WeakODRLinkage: 819 return 17; 820 case GlobalValue::LinkOnceODRLinkage: 821 return 19; 822 case GlobalValue::AvailableExternallyLinkage: 823 return 12; 824 } 825 llvm_unreachable("Invalid linkage"); 826 } 827 828 unsigned DXILBitcodeWriter::getEncodedLinkage(const GlobalValue &GV) { 829 return getEncodedLinkage(GV.getLinkage()); 830 } 831 832 unsigned DXILBitcodeWriter::getEncodedVisibility(const GlobalValue &GV) { 833 switch (GV.getVisibility()) { 834 case GlobalValue::DefaultVisibility: 835 return 0; 836 case GlobalValue::HiddenVisibility: 837 return 1; 838 case GlobalValue::ProtectedVisibility: 839 return 2; 840 } 841 llvm_unreachable("Invalid visibility"); 842 } 843 844 unsigned DXILBitcodeWriter::getEncodedDLLStorageClass(const GlobalValue &GV) { 845 switch (GV.getDLLStorageClass()) { 846 case GlobalValue::DefaultStorageClass: 847 return 0; 848 case GlobalValue::DLLImportStorageClass: 849 return 1; 850 case GlobalValue::DLLExportStorageClass: 851 return 2; 852 } 853 llvm_unreachable("Invalid DLL storage class"); 854 } 855 856 unsigned DXILBitcodeWriter::getEncodedThreadLocalMode(const GlobalValue &GV) { 857 switch (GV.getThreadLocalMode()) { 858 case GlobalVariable::NotThreadLocal: 859 return 0; 860 case GlobalVariable::GeneralDynamicTLSModel: 861 return 1; 862 case GlobalVariable::LocalDynamicTLSModel: 863 return 2; 864 case GlobalVariable::InitialExecTLSModel: 865 return 3; 866 case GlobalVariable::LocalExecTLSModel: 867 return 4; 868 } 869 llvm_unreachable("Invalid TLS model"); 870 } 871 872 unsigned DXILBitcodeWriter::getEncodedComdatSelectionKind(const Comdat &C) { 873 switch (C.getSelectionKind()) { 874 case Comdat::Any: 875 return bitc::COMDAT_SELECTION_KIND_ANY; 876 case Comdat::ExactMatch: 877 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 878 case Comdat::Largest: 879 return bitc::COMDAT_SELECTION_KIND_LARGEST; 880 case Comdat::NoDeduplicate: 881 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 882 case Comdat::SameSize: 883 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 884 } 885 llvm_unreachable("Invalid selection kind"); 886 } 887 888 //////////////////////////////////////////////////////////////////////////////// 889 /// Begin DXILBitcodeWriter Implementation 890 //////////////////////////////////////////////////////////////////////////////// 891 892 void DXILBitcodeWriter::writeAttributeGroupTable() { 893 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps = 894 VE.getAttributeGroups(); 895 if (AttrGrps.empty()) 896 return; 897 898 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 899 900 SmallVector<uint64_t, 64> Record; 901 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) { 902 unsigned AttrListIndex = Pair.first; 903 AttributeSet AS = Pair.second; 904 Record.push_back(VE.getAttributeGroupID(Pair)); 905 Record.push_back(AttrListIndex); 906 907 for (Attribute Attr : AS) { 908 if (Attr.isEnumAttribute()) { 909 uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum()); 910 assert(Val <= bitc::ATTR_KIND_ARGMEMONLY && 911 "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY"); 912 Record.push_back(0); 913 Record.push_back(Val); 914 } else if (Attr.isIntAttribute()) { 915 uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum()); 916 assert(Val <= bitc::ATTR_KIND_ARGMEMONLY && 917 "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY"); 918 Record.push_back(1); 919 Record.push_back(Val); 920 Record.push_back(Attr.getValueAsInt()); 921 } else { 922 StringRef Kind = Attr.getKindAsString(); 923 StringRef Val = Attr.getValueAsString(); 924 925 Record.push_back(Val.empty() ? 3 : 4); 926 Record.append(Kind.begin(), Kind.end()); 927 Record.push_back(0); 928 if (!Val.empty()) { 929 Record.append(Val.begin(), Val.end()); 930 Record.push_back(0); 931 } 932 } 933 } 934 935 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 936 Record.clear(); 937 } 938 939 Stream.ExitBlock(); 940 } 941 942 void DXILBitcodeWriter::writeAttributeTable() { 943 const std::vector<AttributeList> &Attrs = VE.getAttributeLists(); 944 if (Attrs.empty()) 945 return; 946 947 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 948 949 SmallVector<uint64_t, 64> Record; 950 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 951 AttributeList AL = Attrs[i]; 952 for (unsigned i : AL.indexes()) { 953 AttributeSet AS = AL.getAttributes(i); 954 if (AS.hasAttributes()) 955 Record.push_back(VE.getAttributeGroupID({i, AS})); 956 } 957 958 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 959 Record.clear(); 960 } 961 962 Stream.ExitBlock(); 963 } 964 965 /// WriteTypeTable - Write out the type table for a module. 966 void DXILBitcodeWriter::writeTypeTable() { 967 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 968 969 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 970 SmallVector<uint64_t, 64> TypeVals; 971 972 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies(); 973 974 // Abbrev for TYPE_CODE_POINTER. 975 auto Abbv = std::make_shared<BitCodeAbbrev>(); 976 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 977 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 978 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 979 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 980 981 // Abbrev for TYPE_CODE_FUNCTION. 982 Abbv = std::make_shared<BitCodeAbbrev>(); 983 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 987 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 988 989 // Abbrev for TYPE_CODE_STRUCT_ANON. 990 Abbv = std::make_shared<BitCodeAbbrev>(); 991 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 995 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 996 997 // Abbrev for TYPE_CODE_STRUCT_NAME. 998 Abbv = std::make_shared<BitCodeAbbrev>(); 999 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 1000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1002 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1003 1004 // Abbrev for TYPE_CODE_STRUCT_NAMED. 1005 Abbv = std::make_shared<BitCodeAbbrev>(); 1006 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 1007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 1008 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1009 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1010 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1011 1012 // Abbrev for TYPE_CODE_ARRAY. 1013 Abbv = std::make_shared<BitCodeAbbrev>(); 1014 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 1015 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 1016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 1017 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1018 1019 // Emit an entry count so the reader can reserve space. 1020 TypeVals.push_back(TypeList.size()); 1021 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 1022 TypeVals.clear(); 1023 1024 // Loop over all of the types, emitting each in turn. 1025 for (Type *T : TypeList) { 1026 int AbbrevToUse = 0; 1027 unsigned Code = 0; 1028 1029 switch (T->getTypeID()) { 1030 case Type::BFloatTyID: 1031 case Type::X86_AMXTyID: 1032 case Type::TokenTyID: 1033 llvm_unreachable("These should never be used!!!"); 1034 break; 1035 case Type::VoidTyID: 1036 Code = bitc::TYPE_CODE_VOID; 1037 break; 1038 case Type::HalfTyID: 1039 Code = bitc::TYPE_CODE_HALF; 1040 break; 1041 case Type::FloatTyID: 1042 Code = bitc::TYPE_CODE_FLOAT; 1043 break; 1044 case Type::DoubleTyID: 1045 Code = bitc::TYPE_CODE_DOUBLE; 1046 break; 1047 case Type::X86_FP80TyID: 1048 Code = bitc::TYPE_CODE_X86_FP80; 1049 break; 1050 case Type::FP128TyID: 1051 Code = bitc::TYPE_CODE_FP128; 1052 break; 1053 case Type::PPC_FP128TyID: 1054 Code = bitc::TYPE_CODE_PPC_FP128; 1055 break; 1056 case Type::LabelTyID: 1057 Code = bitc::TYPE_CODE_LABEL; 1058 break; 1059 case Type::MetadataTyID: 1060 Code = bitc::TYPE_CODE_METADATA; 1061 break; 1062 case Type::X86_MMXTyID: 1063 Code = bitc::TYPE_CODE_X86_MMX; 1064 break; 1065 case Type::IntegerTyID: 1066 // INTEGER: [width] 1067 Code = bitc::TYPE_CODE_INTEGER; 1068 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 1069 break; 1070 case Type::DXILPointerTyID: { 1071 TypedPointerType *PTy = cast<TypedPointerType>(T); 1072 // POINTER: [pointee type, address space] 1073 Code = bitc::TYPE_CODE_POINTER; 1074 TypeVals.push_back(getTypeID(PTy->getElementType())); 1075 unsigned AddressSpace = PTy->getAddressSpace(); 1076 TypeVals.push_back(AddressSpace); 1077 if (AddressSpace == 0) 1078 AbbrevToUse = PtrAbbrev; 1079 break; 1080 } 1081 case Type::PointerTyID: { 1082 PointerType *PTy = cast<PointerType>(T); 1083 // POINTER: [pointee type, address space] 1084 Code = bitc::TYPE_CODE_POINTER; 1085 // Emitting an empty struct type for the opaque pointer's type allows 1086 // this to be order-independent. Non-struct types must be emitted in 1087 // bitcode before they can be referenced. 1088 if (PTy->isOpaquePointerTy()) { 1089 TypeVals.push_back(false); 1090 Code = bitc::TYPE_CODE_OPAQUE; 1091 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, 1092 "dxilOpaquePtrReservedName", StructNameAbbrev); 1093 } else { 1094 TypeVals.push_back(getTypeID(PTy->getNonOpaquePointerElementType())); 1095 unsigned AddressSpace = PTy->getAddressSpace(); 1096 TypeVals.push_back(AddressSpace); 1097 if (AddressSpace == 0) 1098 AbbrevToUse = PtrAbbrev; 1099 } 1100 break; 1101 } 1102 case Type::FunctionTyID: { 1103 FunctionType *FT = cast<FunctionType>(T); 1104 // FUNCTION: [isvararg, retty, paramty x N] 1105 Code = bitc::TYPE_CODE_FUNCTION; 1106 TypeVals.push_back(FT->isVarArg()); 1107 TypeVals.push_back(getTypeID(FT->getReturnType())); 1108 for (Type *PTy : FT->params()) 1109 TypeVals.push_back(getTypeID(PTy)); 1110 AbbrevToUse = FunctionAbbrev; 1111 break; 1112 } 1113 case Type::StructTyID: { 1114 StructType *ST = cast<StructType>(T); 1115 // STRUCT: [ispacked, eltty x N] 1116 TypeVals.push_back(ST->isPacked()); 1117 // Output all of the element types. 1118 for (Type *ElTy : ST->elements()) 1119 TypeVals.push_back(getTypeID(ElTy)); 1120 1121 if (ST->isLiteral()) { 1122 Code = bitc::TYPE_CODE_STRUCT_ANON; 1123 AbbrevToUse = StructAnonAbbrev; 1124 } else { 1125 if (ST->isOpaque()) { 1126 Code = bitc::TYPE_CODE_OPAQUE; 1127 } else { 1128 Code = bitc::TYPE_CODE_STRUCT_NAMED; 1129 AbbrevToUse = StructNamedAbbrev; 1130 } 1131 1132 // Emit the name if it is present. 1133 if (!ST->getName().empty()) 1134 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 1135 StructNameAbbrev); 1136 } 1137 break; 1138 } 1139 case Type::ArrayTyID: { 1140 ArrayType *AT = cast<ArrayType>(T); 1141 // ARRAY: [numelts, eltty] 1142 Code = bitc::TYPE_CODE_ARRAY; 1143 TypeVals.push_back(AT->getNumElements()); 1144 TypeVals.push_back(getTypeID(AT->getElementType())); 1145 AbbrevToUse = ArrayAbbrev; 1146 break; 1147 } 1148 case Type::FixedVectorTyID: 1149 case Type::ScalableVectorTyID: { 1150 VectorType *VT = cast<VectorType>(T); 1151 // VECTOR [numelts, eltty] 1152 Code = bitc::TYPE_CODE_VECTOR; 1153 TypeVals.push_back(VT->getElementCount().getKnownMinValue()); 1154 TypeVals.push_back(getTypeID(VT->getElementType())); 1155 break; 1156 } 1157 } 1158 1159 // Emit the finished record. 1160 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 1161 TypeVals.clear(); 1162 } 1163 1164 Stream.ExitBlock(); 1165 } 1166 1167 void DXILBitcodeWriter::writeComdats() { 1168 SmallVector<uint16_t, 64> Vals; 1169 for (const Comdat *C : VE.getComdats()) { 1170 // COMDAT: [selection_kind, name] 1171 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1172 size_t Size = C->getName().size(); 1173 assert(isUInt<16>(Size)); 1174 Vals.push_back(Size); 1175 for (char Chr : C->getName()) 1176 Vals.push_back((unsigned char)Chr); 1177 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1178 Vals.clear(); 1179 } 1180 } 1181 1182 void DXILBitcodeWriter::writeValueSymbolTableForwardDecl() {} 1183 1184 /// Emit top-level description of module, including target triple, inline asm, 1185 /// descriptors for global variables, and function prototype info. 1186 /// Returns the bit offset to backpatch with the location of the real VST. 1187 void DXILBitcodeWriter::writeModuleInfo() { 1188 // Emit various pieces of data attached to a module. 1189 if (!M.getTargetTriple().empty()) 1190 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1191 0 /*TODO*/); 1192 const std::string &DL = M.getDataLayoutStr(); 1193 if (!DL.empty()) 1194 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1195 if (!M.getModuleInlineAsm().empty()) 1196 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1197 0 /*TODO*/); 1198 1199 // Emit information about sections and GC, computing how many there are. Also 1200 // compute the maximum alignment value. 1201 std::map<std::string, unsigned> SectionMap; 1202 std::map<std::string, unsigned> GCMap; 1203 MaybeAlign MaxAlignment; 1204 unsigned MaxGlobalType = 0; 1205 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) { 1206 if (A) 1207 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A); 1208 }; 1209 for (const GlobalVariable &GV : M.globals()) { 1210 UpdateMaxAlignment(GV.getAlign()); 1211 MaxGlobalType = std::max(MaxGlobalType, getTypeID(GV.getValueType(), &GV)); 1212 if (GV.hasSection()) { 1213 // Give section names unique ID's. 1214 unsigned &Entry = SectionMap[std::string(GV.getSection())]; 1215 if (!Entry) { 1216 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, 1217 GV.getSection(), 0 /*TODO*/); 1218 Entry = SectionMap.size(); 1219 } 1220 } 1221 } 1222 for (const Function &F : M) { 1223 UpdateMaxAlignment(F.getAlign()); 1224 if (F.hasSection()) { 1225 // Give section names unique ID's. 1226 unsigned &Entry = SectionMap[std::string(F.getSection())]; 1227 if (!Entry) { 1228 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1229 0 /*TODO*/); 1230 Entry = SectionMap.size(); 1231 } 1232 } 1233 if (F.hasGC()) { 1234 // Same for GC names. 1235 unsigned &Entry = GCMap[F.getGC()]; 1236 if (!Entry) { 1237 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(), 1238 0 /*TODO*/); 1239 Entry = GCMap.size(); 1240 } 1241 } 1242 } 1243 1244 // Emit abbrev for globals, now that we know # sections and max alignment. 1245 unsigned SimpleGVarAbbrev = 0; 1246 if (!M.global_empty()) { 1247 // Add an abbrev for common globals with no visibility or thread 1248 // localness. 1249 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1250 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1252 Log2_32_Ceil(MaxGlobalType + 1))); 1253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1254 //| explicitType << 1 1255 //| constant 1256 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1258 if (!MaxAlignment) // Alignment. 1259 Abbv->Add(BitCodeAbbrevOp(0)); 1260 else { 1261 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment); 1262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1263 Log2_32_Ceil(MaxEncAlignment + 1))); 1264 } 1265 if (SectionMap.empty()) // Section. 1266 Abbv->Add(BitCodeAbbrevOp(0)); 1267 else 1268 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1269 Log2_32_Ceil(SectionMap.size() + 1))); 1270 // Don't bother emitting vis + thread local. 1271 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1272 } 1273 1274 // Emit the global variable information. 1275 SmallVector<unsigned, 64> Vals; 1276 for (const GlobalVariable &GV : M.globals()) { 1277 unsigned AbbrevToUse = 0; 1278 1279 // GLOBALVAR: [type, isconst, initid, 1280 // linkage, alignment, section, visibility, threadlocal, 1281 // unnamed_addr, externally_initialized, dllstorageclass, 1282 // comdat] 1283 Vals.push_back(getTypeID(GV.getValueType(), &GV)); 1284 Vals.push_back( 1285 GV.getType()->getAddressSpace() << 2 | 2 | 1286 (GV.isConstant() ? 1 : 0)); // HLSL Change - bitwise | was used with 1287 // unsigned int and bool 1288 Vals.push_back( 1289 GV.isDeclaration() ? 0 : (VE.getValueID(GV.getInitializer()) + 1)); 1290 Vals.push_back(getEncodedLinkage(GV)); 1291 Vals.push_back(getEncodedAlign(GV.getAlign())); 1292 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())] 1293 : 0); 1294 if (GV.isThreadLocal() || 1295 GV.getVisibility() != GlobalValue::DefaultVisibility || 1296 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1297 GV.isExternallyInitialized() || 1298 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1299 GV.hasComdat()) { 1300 Vals.push_back(getEncodedVisibility(GV)); 1301 Vals.push_back(getEncodedThreadLocalMode(GV)); 1302 Vals.push_back(GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1303 Vals.push_back(GV.isExternallyInitialized()); 1304 Vals.push_back(getEncodedDLLStorageClass(GV)); 1305 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1306 } else { 1307 AbbrevToUse = SimpleGVarAbbrev; 1308 } 1309 1310 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1311 Vals.clear(); 1312 } 1313 1314 // Emit the function proto information. 1315 for (const Function &F : M) { 1316 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 1317 // section, visibility, gc, unnamed_addr, prologuedata, 1318 // dllstorageclass, comdat, prefixdata, personalityfn] 1319 Vals.push_back(getTypeID(F.getFunctionType(), &F)); 1320 Vals.push_back(F.getCallingConv()); 1321 Vals.push_back(F.isDeclaration()); 1322 Vals.push_back(getEncodedLinkage(F)); 1323 Vals.push_back(VE.getAttributeListID(F.getAttributes())); 1324 Vals.push_back(getEncodedAlign(F.getAlign())); 1325 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())] 1326 : 0); 1327 Vals.push_back(getEncodedVisibility(F)); 1328 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1329 Vals.push_back(F.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1330 Vals.push_back( 1331 F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) : 0); 1332 Vals.push_back(getEncodedDLLStorageClass(F)); 1333 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1334 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1335 : 0); 1336 Vals.push_back( 1337 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1338 1339 unsigned AbbrevToUse = 0; 1340 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1341 Vals.clear(); 1342 } 1343 1344 // Emit the alias information. 1345 for (const GlobalAlias &A : M.aliases()) { 1346 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1347 Vals.push_back(getTypeID(A.getValueType(), &A)); 1348 Vals.push_back(VE.getValueID(A.getAliasee())); 1349 Vals.push_back(getEncodedLinkage(A)); 1350 Vals.push_back(getEncodedVisibility(A)); 1351 Vals.push_back(getEncodedDLLStorageClass(A)); 1352 Vals.push_back(getEncodedThreadLocalMode(A)); 1353 Vals.push_back(A.getUnnamedAddr() != GlobalValue::UnnamedAddr::None); 1354 unsigned AbbrevToUse = 0; 1355 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS_OLD, Vals, AbbrevToUse); 1356 Vals.clear(); 1357 } 1358 } 1359 1360 void DXILBitcodeWriter::writeValueAsMetadata( 1361 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1362 // Mimic an MDNode with a value as one operand. 1363 Value *V = MD->getValue(); 1364 Type *Ty = V->getType(); 1365 if (Function *F = dyn_cast<Function>(V)) 1366 Ty = TypedPointerType::get(F->getFunctionType(), F->getAddressSpace()); 1367 else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 1368 Ty = TypedPointerType::get(GV->getValueType(), GV->getAddressSpace()); 1369 Record.push_back(getTypeID(Ty)); 1370 Record.push_back(VE.getValueID(V)); 1371 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1372 Record.clear(); 1373 } 1374 1375 void DXILBitcodeWriter::writeMDTuple(const MDTuple *N, 1376 SmallVectorImpl<uint64_t> &Record, 1377 unsigned Abbrev) { 1378 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1379 Metadata *MD = N->getOperand(i); 1380 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1381 "Unexpected function-local metadata"); 1382 Record.push_back(VE.getMetadataOrNullID(MD)); 1383 } 1384 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1385 : bitc::METADATA_NODE, 1386 Record, Abbrev); 1387 Record.clear(); 1388 } 1389 1390 void DXILBitcodeWriter::writeDILocation(const DILocation *N, 1391 SmallVectorImpl<uint64_t> &Record, 1392 unsigned &Abbrev) { 1393 if (!Abbrev) 1394 Abbrev = createDILocationAbbrev(); 1395 Record.push_back(N->isDistinct()); 1396 Record.push_back(N->getLine()); 1397 Record.push_back(N->getColumn()); 1398 Record.push_back(VE.getMetadataID(N->getScope())); 1399 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1400 1401 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1402 Record.clear(); 1403 } 1404 1405 static uint64_t rotateSign(APInt Val) { 1406 int64_t I = Val.getSExtValue(); 1407 uint64_t U = I; 1408 return I < 0 ? ~(U << 1) : U << 1; 1409 } 1410 1411 static uint64_t rotateSign(DISubrange::BoundType Val) { 1412 return rotateSign(Val.get<ConstantInt *>()->getValue()); 1413 } 1414 1415 void DXILBitcodeWriter::writeDISubrange(const DISubrange *N, 1416 SmallVectorImpl<uint64_t> &Record, 1417 unsigned Abbrev) { 1418 Record.push_back(N->isDistinct()); 1419 Record.push_back( 1420 N->getCount().get<ConstantInt *>()->getValue().getSExtValue()); 1421 Record.push_back(rotateSign(N->getLowerBound())); 1422 1423 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1424 Record.clear(); 1425 } 1426 1427 void DXILBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1428 SmallVectorImpl<uint64_t> &Record, 1429 unsigned Abbrev) { 1430 Record.push_back(N->isDistinct()); 1431 Record.push_back(rotateSign(N->getValue())); 1432 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1433 1434 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1435 Record.clear(); 1436 } 1437 1438 void DXILBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1439 SmallVectorImpl<uint64_t> &Record, 1440 unsigned Abbrev) { 1441 Record.push_back(N->isDistinct()); 1442 Record.push_back(N->getTag()); 1443 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1444 Record.push_back(N->getSizeInBits()); 1445 Record.push_back(N->getAlignInBits()); 1446 Record.push_back(N->getEncoding()); 1447 1448 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1449 Record.clear(); 1450 } 1451 1452 void DXILBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1453 SmallVectorImpl<uint64_t> &Record, 1454 unsigned Abbrev) { 1455 Record.push_back(N->isDistinct()); 1456 Record.push_back(N->getTag()); 1457 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1458 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1459 Record.push_back(N->getLine()); 1460 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1461 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1462 Record.push_back(N->getSizeInBits()); 1463 Record.push_back(N->getAlignInBits()); 1464 Record.push_back(N->getOffsetInBits()); 1465 Record.push_back(N->getFlags()); 1466 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1467 1468 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1469 Record.clear(); 1470 } 1471 1472 void DXILBitcodeWriter::writeDICompositeType(const DICompositeType *N, 1473 SmallVectorImpl<uint64_t> &Record, 1474 unsigned Abbrev) { 1475 Record.push_back(N->isDistinct()); 1476 Record.push_back(N->getTag()); 1477 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1478 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1479 Record.push_back(N->getLine()); 1480 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1481 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1482 Record.push_back(N->getSizeInBits()); 1483 Record.push_back(N->getAlignInBits()); 1484 Record.push_back(N->getOffsetInBits()); 1485 Record.push_back(N->getFlags()); 1486 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1487 Record.push_back(N->getRuntimeLang()); 1488 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1489 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1490 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1491 1492 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1493 Record.clear(); 1494 } 1495 1496 void DXILBitcodeWriter::writeDISubroutineType(const DISubroutineType *N, 1497 SmallVectorImpl<uint64_t> &Record, 1498 unsigned Abbrev) { 1499 Record.push_back(N->isDistinct()); 1500 Record.push_back(N->getFlags()); 1501 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1502 1503 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1504 Record.clear(); 1505 } 1506 1507 void DXILBitcodeWriter::writeDIFile(const DIFile *N, 1508 SmallVectorImpl<uint64_t> &Record, 1509 unsigned Abbrev) { 1510 Record.push_back(N->isDistinct()); 1511 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1512 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1513 1514 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1515 Record.clear(); 1516 } 1517 1518 void DXILBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1519 SmallVectorImpl<uint64_t> &Record, 1520 unsigned Abbrev) { 1521 Record.push_back(N->isDistinct()); 1522 Record.push_back(N->getSourceLanguage()); 1523 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1524 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1525 Record.push_back(N->isOptimized()); 1526 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1527 Record.push_back(N->getRuntimeVersion()); 1528 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1529 Record.push_back(N->getEmissionKind()); 1530 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1531 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1532 Record.push_back(/* subprograms */ 0); 1533 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1534 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1535 Record.push_back(N->getDWOId()); 1536 1537 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1538 Record.clear(); 1539 } 1540 1541 void DXILBitcodeWriter::writeDISubprogram(const DISubprogram *N, 1542 SmallVectorImpl<uint64_t> &Record, 1543 unsigned Abbrev) { 1544 Record.push_back(N->isDistinct()); 1545 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1546 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1547 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1548 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1549 Record.push_back(N->getLine()); 1550 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1551 Record.push_back(N->isLocalToUnit()); 1552 Record.push_back(N->isDefinition()); 1553 Record.push_back(N->getScopeLine()); 1554 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1555 Record.push_back(N->getVirtuality()); 1556 Record.push_back(N->getVirtualIndex()); 1557 Record.push_back(N->getFlags()); 1558 Record.push_back(N->isOptimized()); 1559 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 1560 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1561 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1562 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get())); 1563 1564 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1565 Record.clear(); 1566 } 1567 1568 void DXILBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 1569 SmallVectorImpl<uint64_t> &Record, 1570 unsigned Abbrev) { 1571 Record.push_back(N->isDistinct()); 1572 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1573 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1574 Record.push_back(N->getLine()); 1575 Record.push_back(N->getColumn()); 1576 1577 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1578 Record.clear(); 1579 } 1580 1581 void DXILBitcodeWriter::writeDILexicalBlockFile( 1582 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record, 1583 unsigned Abbrev) { 1584 Record.push_back(N->isDistinct()); 1585 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1586 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1587 Record.push_back(N->getDiscriminator()); 1588 1589 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1590 Record.clear(); 1591 } 1592 1593 void DXILBitcodeWriter::writeDINamespace(const DINamespace *N, 1594 SmallVectorImpl<uint64_t> &Record, 1595 unsigned Abbrev) { 1596 Record.push_back(N->isDistinct()); 1597 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1598 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1599 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1600 Record.push_back(/* line number */ 0); 1601 1602 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1603 Record.clear(); 1604 } 1605 1606 void DXILBitcodeWriter::writeDIModule(const DIModule *N, 1607 SmallVectorImpl<uint64_t> &Record, 1608 unsigned Abbrev) { 1609 Record.push_back(N->isDistinct()); 1610 for (auto &I : N->operands()) 1611 Record.push_back(VE.getMetadataOrNullID(I)); 1612 1613 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1614 Record.clear(); 1615 } 1616 1617 void DXILBitcodeWriter::writeDITemplateTypeParameter( 1618 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 1619 unsigned Abbrev) { 1620 Record.push_back(N->isDistinct()); 1621 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1622 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1623 1624 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1625 Record.clear(); 1626 } 1627 1628 void DXILBitcodeWriter::writeDITemplateValueParameter( 1629 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 1630 unsigned Abbrev) { 1631 Record.push_back(N->isDistinct()); 1632 Record.push_back(N->getTag()); 1633 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1634 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1635 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1636 1637 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1638 Record.clear(); 1639 } 1640 1641 void DXILBitcodeWriter::writeDIGlobalVariable(const DIGlobalVariable *N, 1642 SmallVectorImpl<uint64_t> &Record, 1643 unsigned Abbrev) { 1644 Record.push_back(N->isDistinct()); 1645 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1646 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1647 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1648 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1649 Record.push_back(N->getLine()); 1650 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1651 Record.push_back(N->isLocalToUnit()); 1652 Record.push_back(N->isDefinition()); 1653 Record.push_back(/* N->getRawVariable() */ 0); 1654 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1655 1656 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1657 Record.clear(); 1658 } 1659 1660 void DXILBitcodeWriter::writeDILocalVariable(const DILocalVariable *N, 1661 SmallVectorImpl<uint64_t> &Record, 1662 unsigned Abbrev) { 1663 Record.push_back(N->isDistinct()); 1664 Record.push_back(N->getTag()); 1665 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1666 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1667 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1668 Record.push_back(N->getLine()); 1669 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1670 Record.push_back(N->getArg()); 1671 Record.push_back(N->getFlags()); 1672 1673 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1674 Record.clear(); 1675 } 1676 1677 void DXILBitcodeWriter::writeDIExpression(const DIExpression *N, 1678 SmallVectorImpl<uint64_t> &Record, 1679 unsigned Abbrev) { 1680 Record.reserve(N->getElements().size() + 1); 1681 1682 Record.push_back(N->isDistinct()); 1683 Record.append(N->elements_begin(), N->elements_end()); 1684 1685 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1686 Record.clear(); 1687 } 1688 1689 void DXILBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 1690 SmallVectorImpl<uint64_t> &Record, 1691 unsigned Abbrev) { 1692 llvm_unreachable("DXIL does not support objc!!!"); 1693 } 1694 1695 void DXILBitcodeWriter::writeDIImportedEntity(const DIImportedEntity *N, 1696 SmallVectorImpl<uint64_t> &Record, 1697 unsigned Abbrev) { 1698 Record.push_back(N->isDistinct()); 1699 Record.push_back(N->getTag()); 1700 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1701 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 1702 Record.push_back(N->getLine()); 1703 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1704 1705 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 1706 Record.clear(); 1707 } 1708 1709 unsigned DXILBitcodeWriter::createDILocationAbbrev() { 1710 // Abbrev for METADATA_LOCATION. 1711 // 1712 // Assume the column is usually under 128, and always output the inlined-at 1713 // location (it's never more expensive than building an array size 1). 1714 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1715 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1721 return Stream.EmitAbbrev(std::move(Abbv)); 1722 } 1723 1724 unsigned DXILBitcodeWriter::createGenericDINodeAbbrev() { 1725 // Abbrev for METADATA_GENERIC_DEBUG. 1726 // 1727 // Assume the column is usually under 128, and always output the inlined-at 1728 // location (it's never more expensive than building an array size 1). 1729 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1730 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1734 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1736 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1737 return Stream.EmitAbbrev(std::move(Abbv)); 1738 } 1739 1740 void DXILBitcodeWriter::writeMetadataRecords(ArrayRef<const Metadata *> MDs, 1741 SmallVectorImpl<uint64_t> &Record, 1742 std::vector<unsigned> *MDAbbrevs, 1743 std::vector<uint64_t> *IndexPos) { 1744 if (MDs.empty()) 1745 return; 1746 1747 // Initialize MDNode abbreviations. 1748 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 1749 #include "llvm/IR/Metadata.def" 1750 1751 for (const Metadata *MD : MDs) { 1752 if (IndexPos) 1753 IndexPos->push_back(Stream.GetCurrentBitNo()); 1754 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 1755 assert(N->isResolved() && "Expected forward references to be resolved"); 1756 1757 switch (N->getMetadataID()) { 1758 default: 1759 llvm_unreachable("Invalid MDNode subclass"); 1760 #define HANDLE_MDNODE_LEAF(CLASS) \ 1761 case Metadata::CLASS##Kind: \ 1762 if (MDAbbrevs) \ 1763 write##CLASS(cast<CLASS>(N), Record, \ 1764 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \ 1765 else \ 1766 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 1767 continue; 1768 #include "llvm/IR/Metadata.def" 1769 } 1770 } 1771 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 1772 } 1773 } 1774 1775 unsigned DXILBitcodeWriter::createMetadataStringsAbbrev() { 1776 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1777 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING_OLD)); 1778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1780 return Stream.EmitAbbrev(std::move(Abbv)); 1781 } 1782 1783 void DXILBitcodeWriter::writeMetadataStrings( 1784 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 1785 for (const Metadata *MD : Strings) { 1786 const MDString *MDS = cast<MDString>(MD); 1787 // Code: [strchar x N] 1788 Record.append(MDS->bytes_begin(), MDS->bytes_end()); 1789 1790 // Emit the finished record. 1791 Stream.EmitRecord(bitc::METADATA_STRING_OLD, Record, 1792 createMetadataStringsAbbrev()); 1793 Record.clear(); 1794 } 1795 } 1796 1797 void DXILBitcodeWriter::writeModuleMetadata() { 1798 if (!VE.hasMDs() && M.named_metadata_empty()) 1799 return; 1800 1801 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 5); 1802 1803 // Emit all abbrevs upfront, so that the reader can jump in the middle of the 1804 // block and load any metadata. 1805 std::vector<unsigned> MDAbbrevs; 1806 1807 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne); 1808 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev(); 1809 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] = 1810 createGenericDINodeAbbrev(); 1811 1812 unsigned NameAbbrev = 0; 1813 if (!M.named_metadata_empty()) { 1814 // Abbrev for METADATA_NAME. 1815 std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>(); 1816 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 1817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1818 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1819 NameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1820 } 1821 1822 SmallVector<uint64_t, 64> Record; 1823 writeMetadataStrings(VE.getMDStrings(), Record); 1824 1825 std::vector<uint64_t> IndexPos; 1826 IndexPos.reserve(VE.getNonMDStrings().size()); 1827 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos); 1828 1829 // Write named metadata. 1830 for (const NamedMDNode &NMD : M.named_metadata()) { 1831 // Write name. 1832 StringRef Str = NMD.getName(); 1833 Record.append(Str.bytes_begin(), Str.bytes_end()); 1834 Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev); 1835 Record.clear(); 1836 1837 // Write named metadata operands. 1838 for (const MDNode *N : NMD.operands()) 1839 Record.push_back(VE.getMetadataID(N)); 1840 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 1841 Record.clear(); 1842 } 1843 1844 Stream.ExitBlock(); 1845 } 1846 1847 void DXILBitcodeWriter::writeFunctionMetadata(const Function &F) { 1848 if (!VE.hasMDs()) 1849 return; 1850 1851 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4); 1852 SmallVector<uint64_t, 64> Record; 1853 writeMetadataStrings(VE.getMDStrings(), Record); 1854 writeMetadataRecords(VE.getNonMDStrings(), Record); 1855 Stream.ExitBlock(); 1856 } 1857 1858 void DXILBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 1859 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 1860 1861 SmallVector<uint64_t, 64> Record; 1862 1863 // Write metadata attachments 1864 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 1865 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1866 F.getAllMetadata(MDs); 1867 if (!MDs.empty()) { 1868 for (const auto &I : MDs) { 1869 Record.push_back(I.first); 1870 Record.push_back(VE.getMetadataID(I.second)); 1871 } 1872 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1873 Record.clear(); 1874 } 1875 1876 for (const BasicBlock &BB : F) 1877 for (const Instruction &I : BB) { 1878 MDs.clear(); 1879 I.getAllMetadataOtherThanDebugLoc(MDs); 1880 1881 // If no metadata, ignore instruction. 1882 if (MDs.empty()) 1883 continue; 1884 1885 Record.push_back(VE.getInstructionID(&I)); 1886 1887 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 1888 Record.push_back(MDs[i].first); 1889 Record.push_back(VE.getMetadataID(MDs[i].second)); 1890 } 1891 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 1892 Record.clear(); 1893 } 1894 1895 Stream.ExitBlock(); 1896 } 1897 1898 void DXILBitcodeWriter::writeModuleMetadataKinds() { 1899 SmallVector<uint64_t, 64> Record; 1900 1901 // Write metadata kinds 1902 // METADATA_KIND - [n x [id, name]] 1903 SmallVector<StringRef, 8> Names; 1904 M.getMDKindNames(Names); 1905 1906 if (Names.empty()) 1907 return; 1908 1909 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 1910 1911 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 1912 Record.push_back(MDKindID); 1913 StringRef KName = Names[MDKindID]; 1914 Record.append(KName.begin(), KName.end()); 1915 1916 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 1917 Record.clear(); 1918 } 1919 1920 Stream.ExitBlock(); 1921 } 1922 1923 void DXILBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 1924 bool isGlobal) { 1925 if (FirstVal == LastVal) 1926 return; 1927 1928 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 1929 1930 unsigned AggregateAbbrev = 0; 1931 unsigned String8Abbrev = 0; 1932 unsigned CString7Abbrev = 0; 1933 unsigned CString6Abbrev = 0; 1934 // If this is a constant pool for the module, emit module-specific abbrevs. 1935 if (isGlobal) { 1936 // Abbrev for CST_CODE_AGGREGATE. 1937 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1938 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 1939 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1940 Abbv->Add( 1941 BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal + 1))); 1942 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1943 1944 // Abbrev for CST_CODE_STRING. 1945 Abbv = std::make_shared<BitCodeAbbrev>(); 1946 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 1947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1949 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1950 // Abbrev for CST_CODE_CSTRING. 1951 Abbv = std::make_shared<BitCodeAbbrev>(); 1952 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1954 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1955 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1956 // Abbrev for CST_CODE_CSTRING. 1957 Abbv = std::make_shared<BitCodeAbbrev>(); 1958 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 1959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1961 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 1962 } 1963 1964 SmallVector<uint64_t, 64> Record; 1965 1966 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1967 Type *LastTy = nullptr; 1968 for (unsigned i = FirstVal; i != LastVal; ++i) { 1969 const Value *V = Vals[i].first; 1970 // If we need to switch types, do so now. 1971 if (V->getType() != LastTy) { 1972 LastTy = V->getType(); 1973 Record.push_back(getTypeID(LastTy)); 1974 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 1975 CONSTANTS_SETTYPE_ABBREV); 1976 Record.clear(); 1977 } 1978 1979 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1980 Record.push_back(unsigned(IA->hasSideEffects()) | 1981 unsigned(IA->isAlignStack()) << 1 | 1982 unsigned(IA->getDialect() & 1) << 2); 1983 1984 // Add the asm string. 1985 const std::string &AsmStr = IA->getAsmString(); 1986 Record.push_back(AsmStr.size()); 1987 Record.append(AsmStr.begin(), AsmStr.end()); 1988 1989 // Add the constraint string. 1990 const std::string &ConstraintStr = IA->getConstraintString(); 1991 Record.push_back(ConstraintStr.size()); 1992 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 1993 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 1994 Record.clear(); 1995 continue; 1996 } 1997 const Constant *C = cast<Constant>(V); 1998 unsigned Code = -1U; 1999 unsigned AbbrevToUse = 0; 2000 if (C->isNullValue()) { 2001 Code = bitc::CST_CODE_NULL; 2002 } else if (isa<UndefValue>(C)) { 2003 Code = bitc::CST_CODE_UNDEF; 2004 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 2005 if (IV->getBitWidth() <= 64) { 2006 uint64_t V = IV->getSExtValue(); 2007 emitSignedInt64(Record, V); 2008 Code = bitc::CST_CODE_INTEGER; 2009 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2010 } else { // Wide integers, > 64 bits in size. 2011 // We have an arbitrary precision integer value to write whose 2012 // bit width is > 64. However, in canonical unsigned integer 2013 // format it is likely that the high bits are going to be zero. 2014 // So, we only write the number of active words. 2015 unsigned NWords = IV->getValue().getActiveWords(); 2016 const uint64_t *RawWords = IV->getValue().getRawData(); 2017 for (unsigned i = 0; i != NWords; ++i) { 2018 emitSignedInt64(Record, RawWords[i]); 2019 } 2020 Code = bitc::CST_CODE_WIDE_INTEGER; 2021 } 2022 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2023 Code = bitc::CST_CODE_FLOAT; 2024 Type *Ty = CFP->getType(); 2025 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 2026 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2027 } else if (Ty->isX86_FP80Ty()) { 2028 // api needed to prevent premature destruction 2029 // bits are not in the same order as a normal i80 APInt, compensate. 2030 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2031 const uint64_t *p = api.getRawData(); 2032 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2033 Record.push_back(p[0] & 0xffffLL); 2034 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2035 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2036 const uint64_t *p = api.getRawData(); 2037 Record.push_back(p[0]); 2038 Record.push_back(p[1]); 2039 } else { 2040 assert(0 && "Unknown FP type!"); 2041 } 2042 } else if (isa<ConstantDataSequential>(C) && 2043 cast<ConstantDataSequential>(C)->isString()) { 2044 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2045 // Emit constant strings specially. 2046 unsigned NumElts = Str->getNumElements(); 2047 // If this is a null-terminated string, use the denser CSTRING encoding. 2048 if (Str->isCString()) { 2049 Code = bitc::CST_CODE_CSTRING; 2050 --NumElts; // Don't encode the null, which isn't allowed by char6. 2051 } else { 2052 Code = bitc::CST_CODE_STRING; 2053 AbbrevToUse = String8Abbrev; 2054 } 2055 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2056 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2057 for (unsigned i = 0; i != NumElts; ++i) { 2058 unsigned char V = Str->getElementAsInteger(i); 2059 Record.push_back(V); 2060 isCStr7 &= (V & 128) == 0; 2061 if (isCStrChar6) 2062 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2063 } 2064 2065 if (isCStrChar6) 2066 AbbrevToUse = CString6Abbrev; 2067 else if (isCStr7) 2068 AbbrevToUse = CString7Abbrev; 2069 } else if (const ConstantDataSequential *CDS = 2070 dyn_cast<ConstantDataSequential>(C)) { 2071 Code = bitc::CST_CODE_DATA; 2072 Type *EltTy = CDS->getType()->getArrayElementType(); 2073 if (isa<IntegerType>(EltTy)) { 2074 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2075 Record.push_back(CDS->getElementAsInteger(i)); 2076 } else if (EltTy->isFloatTy()) { 2077 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2078 union { 2079 float F; 2080 uint32_t I; 2081 }; 2082 F = CDS->getElementAsFloat(i); 2083 Record.push_back(I); 2084 } 2085 } else { 2086 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type"); 2087 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2088 union { 2089 double F; 2090 uint64_t I; 2091 }; 2092 F = CDS->getElementAsDouble(i); 2093 Record.push_back(I); 2094 } 2095 } 2096 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) || 2097 isa<ConstantVector>(C)) { 2098 Code = bitc::CST_CODE_AGGREGATE; 2099 for (const Value *Op : C->operands()) 2100 Record.push_back(VE.getValueID(Op)); 2101 AbbrevToUse = AggregateAbbrev; 2102 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2103 switch (CE->getOpcode()) { 2104 default: 2105 if (Instruction::isCast(CE->getOpcode())) { 2106 Code = bitc::CST_CODE_CE_CAST; 2107 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2108 Record.push_back(getTypeID(C->getOperand(0)->getType())); 2109 Record.push_back(VE.getValueID(C->getOperand(0))); 2110 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2111 } else { 2112 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2113 Code = bitc::CST_CODE_CE_BINOP; 2114 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2115 Record.push_back(VE.getValueID(C->getOperand(0))); 2116 Record.push_back(VE.getValueID(C->getOperand(1))); 2117 uint64_t Flags = getOptimizationFlags(CE); 2118 if (Flags != 0) 2119 Record.push_back(Flags); 2120 } 2121 break; 2122 case Instruction::GetElementPtr: { 2123 Code = bitc::CST_CODE_CE_GEP; 2124 const auto *GO = cast<GEPOperator>(C); 2125 if (GO->isInBounds()) 2126 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2127 Record.push_back(getTypeID(GO->getSourceElementType())); 2128 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2129 Record.push_back(getTypeID(C->getOperand(i)->getType())); 2130 Record.push_back(VE.getValueID(C->getOperand(i))); 2131 } 2132 break; 2133 } 2134 case Instruction::Select: 2135 Code = bitc::CST_CODE_CE_SELECT; 2136 Record.push_back(VE.getValueID(C->getOperand(0))); 2137 Record.push_back(VE.getValueID(C->getOperand(1))); 2138 Record.push_back(VE.getValueID(C->getOperand(2))); 2139 break; 2140 case Instruction::ExtractElement: 2141 Code = bitc::CST_CODE_CE_EXTRACTELT; 2142 Record.push_back(getTypeID(C->getOperand(0)->getType())); 2143 Record.push_back(VE.getValueID(C->getOperand(0))); 2144 Record.push_back(getTypeID(C->getOperand(1)->getType())); 2145 Record.push_back(VE.getValueID(C->getOperand(1))); 2146 break; 2147 case Instruction::InsertElement: 2148 Code = bitc::CST_CODE_CE_INSERTELT; 2149 Record.push_back(VE.getValueID(C->getOperand(0))); 2150 Record.push_back(VE.getValueID(C->getOperand(1))); 2151 Record.push_back(getTypeID(C->getOperand(2)->getType())); 2152 Record.push_back(VE.getValueID(C->getOperand(2))); 2153 break; 2154 case Instruction::ShuffleVector: 2155 // If the return type and argument types are the same, this is a 2156 // standard shufflevector instruction. If the types are different, 2157 // then the shuffle is widening or truncating the input vectors, and 2158 // the argument type must also be encoded. 2159 if (C->getType() == C->getOperand(0)->getType()) { 2160 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2161 } else { 2162 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2163 Record.push_back(getTypeID(C->getOperand(0)->getType())); 2164 } 2165 Record.push_back(VE.getValueID(C->getOperand(0))); 2166 Record.push_back(VE.getValueID(C->getOperand(1))); 2167 Record.push_back(VE.getValueID(C->getOperand(2))); 2168 break; 2169 case Instruction::ICmp: 2170 case Instruction::FCmp: 2171 Code = bitc::CST_CODE_CE_CMP; 2172 Record.push_back(getTypeID(C->getOperand(0)->getType())); 2173 Record.push_back(VE.getValueID(C->getOperand(0))); 2174 Record.push_back(VE.getValueID(C->getOperand(1))); 2175 Record.push_back(CE->getPredicate()); 2176 break; 2177 } 2178 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2179 Code = bitc::CST_CODE_BLOCKADDRESS; 2180 Record.push_back(getTypeID(BA->getFunction()->getType())); 2181 Record.push_back(VE.getValueID(BA->getFunction())); 2182 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2183 } else { 2184 #ifndef NDEBUG 2185 C->dump(); 2186 #endif 2187 llvm_unreachable("Unknown constant!"); 2188 } 2189 Stream.EmitRecord(Code, Record, AbbrevToUse); 2190 Record.clear(); 2191 } 2192 2193 Stream.ExitBlock(); 2194 } 2195 2196 void DXILBitcodeWriter::writeModuleConstants() { 2197 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2198 2199 // Find the first constant to emit, which is the first non-globalvalue value. 2200 // We know globalvalues have been emitted by WriteModuleInfo. 2201 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2202 if (!isa<GlobalValue>(Vals[i].first)) { 2203 writeConstants(i, Vals.size(), true); 2204 return; 2205 } 2206 } 2207 } 2208 2209 /// pushValueAndType - The file has to encode both the value and type id for 2210 /// many values, because we need to know what type to create for forward 2211 /// references. However, most operands are not forward references, so this type 2212 /// field is not needed. 2213 /// 2214 /// This function adds V's value ID to Vals. If the value ID is higher than the 2215 /// instruction ID, then it is a forward reference, and it also includes the 2216 /// type ID. The value ID that is written is encoded relative to the InstID. 2217 bool DXILBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2218 SmallVectorImpl<unsigned> &Vals) { 2219 unsigned ValID = VE.getValueID(V); 2220 // Make encoding relative to the InstID. 2221 Vals.push_back(InstID - ValID); 2222 if (ValID >= InstID) { 2223 Vals.push_back(getTypeID(V->getType(), V)); 2224 return true; 2225 } 2226 return false; 2227 } 2228 2229 /// pushValue - Like pushValueAndType, but where the type of the value is 2230 /// omitted (perhaps it was already encoded in an earlier operand). 2231 void DXILBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2232 SmallVectorImpl<unsigned> &Vals) { 2233 unsigned ValID = VE.getValueID(V); 2234 Vals.push_back(InstID - ValID); 2235 } 2236 2237 void DXILBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2238 SmallVectorImpl<uint64_t> &Vals) { 2239 unsigned ValID = VE.getValueID(V); 2240 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2241 emitSignedInt64(Vals, diff); 2242 } 2243 2244 /// WriteInstruction - Emit an instruction 2245 void DXILBitcodeWriter::writeInstruction(const Instruction &I, unsigned InstID, 2246 SmallVectorImpl<unsigned> &Vals) { 2247 unsigned Code = 0; 2248 unsigned AbbrevToUse = 0; 2249 VE.setInstructionID(&I); 2250 switch (I.getOpcode()) { 2251 default: 2252 if (Instruction::isCast(I.getOpcode())) { 2253 Code = bitc::FUNC_CODE_INST_CAST; 2254 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2255 AbbrevToUse = (unsigned)FUNCTION_INST_CAST_ABBREV; 2256 Vals.push_back(getTypeID(I.getType(), &I)); 2257 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2258 } else { 2259 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2260 Code = bitc::FUNC_CODE_INST_BINOP; 2261 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2262 AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_ABBREV; 2263 pushValue(I.getOperand(1), InstID, Vals); 2264 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2265 uint64_t Flags = getOptimizationFlags(&I); 2266 if (Flags != 0) { 2267 if (AbbrevToUse == (unsigned)FUNCTION_INST_BINOP_ABBREV) 2268 AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV; 2269 Vals.push_back(Flags); 2270 } 2271 } 2272 break; 2273 2274 case Instruction::GetElementPtr: { 2275 Code = bitc::FUNC_CODE_INST_GEP; 2276 AbbrevToUse = (unsigned)FUNCTION_INST_GEP_ABBREV; 2277 auto &GEPInst = cast<GetElementPtrInst>(I); 2278 Vals.push_back(GEPInst.isInBounds()); 2279 Vals.push_back(getTypeID(GEPInst.getSourceElementType())); 2280 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2281 pushValueAndType(I.getOperand(i), InstID, Vals); 2282 break; 2283 } 2284 case Instruction::ExtractValue: { 2285 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2286 pushValueAndType(I.getOperand(0), InstID, Vals); 2287 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2288 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2289 break; 2290 } 2291 case Instruction::InsertValue: { 2292 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2293 pushValueAndType(I.getOperand(0), InstID, Vals); 2294 pushValueAndType(I.getOperand(1), InstID, Vals); 2295 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2296 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2297 break; 2298 } 2299 case Instruction::Select: 2300 Code = bitc::FUNC_CODE_INST_VSELECT; 2301 pushValueAndType(I.getOperand(1), InstID, Vals); 2302 pushValue(I.getOperand(2), InstID, Vals); 2303 pushValueAndType(I.getOperand(0), InstID, Vals); 2304 break; 2305 case Instruction::ExtractElement: 2306 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2307 pushValueAndType(I.getOperand(0), InstID, Vals); 2308 pushValueAndType(I.getOperand(1), InstID, Vals); 2309 break; 2310 case Instruction::InsertElement: 2311 Code = bitc::FUNC_CODE_INST_INSERTELT; 2312 pushValueAndType(I.getOperand(0), InstID, Vals); 2313 pushValue(I.getOperand(1), InstID, Vals); 2314 pushValueAndType(I.getOperand(2), InstID, Vals); 2315 break; 2316 case Instruction::ShuffleVector: 2317 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2318 pushValueAndType(I.getOperand(0), InstID, Vals); 2319 pushValue(I.getOperand(1), InstID, Vals); 2320 pushValue(I.getOperand(2), InstID, Vals); 2321 break; 2322 case Instruction::ICmp: 2323 case Instruction::FCmp: { 2324 // compare returning Int1Ty or vector of Int1Ty 2325 Code = bitc::FUNC_CODE_INST_CMP2; 2326 pushValueAndType(I.getOperand(0), InstID, Vals); 2327 pushValue(I.getOperand(1), InstID, Vals); 2328 Vals.push_back(cast<CmpInst>(I).getPredicate()); 2329 uint64_t Flags = getOptimizationFlags(&I); 2330 if (Flags != 0) 2331 Vals.push_back(Flags); 2332 break; 2333 } 2334 2335 case Instruction::Ret: { 2336 Code = bitc::FUNC_CODE_INST_RET; 2337 unsigned NumOperands = I.getNumOperands(); 2338 if (NumOperands == 0) 2339 AbbrevToUse = (unsigned)FUNCTION_INST_RET_VOID_ABBREV; 2340 else if (NumOperands == 1) { 2341 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2342 AbbrevToUse = (unsigned)FUNCTION_INST_RET_VAL_ABBREV; 2343 } else { 2344 for (unsigned i = 0, e = NumOperands; i != e; ++i) 2345 pushValueAndType(I.getOperand(i), InstID, Vals); 2346 } 2347 } break; 2348 case Instruction::Br: { 2349 Code = bitc::FUNC_CODE_INST_BR; 2350 const BranchInst &II = cast<BranchInst>(I); 2351 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 2352 if (II.isConditional()) { 2353 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 2354 pushValue(II.getCondition(), InstID, Vals); 2355 } 2356 } break; 2357 case Instruction::Switch: { 2358 Code = bitc::FUNC_CODE_INST_SWITCH; 2359 const SwitchInst &SI = cast<SwitchInst>(I); 2360 Vals.push_back(getTypeID(SI.getCondition()->getType())); 2361 pushValue(SI.getCondition(), InstID, Vals); 2362 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2363 for (auto Case : SI.cases()) { 2364 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2365 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2366 } 2367 } break; 2368 case Instruction::IndirectBr: 2369 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2370 Vals.push_back(getTypeID(I.getOperand(0)->getType())); 2371 // Encode the address operand as relative, but not the basic blocks. 2372 pushValue(I.getOperand(0), InstID, Vals); 2373 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2374 Vals.push_back(VE.getValueID(I.getOperand(i))); 2375 break; 2376 2377 case Instruction::Invoke: { 2378 const InvokeInst *II = cast<InvokeInst>(&I); 2379 const Value *Callee = II->getCalledOperand(); 2380 FunctionType *FTy = II->getFunctionType(); 2381 Code = bitc::FUNC_CODE_INST_INVOKE; 2382 2383 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 2384 Vals.push_back(II->getCallingConv() | 1 << 13); 2385 Vals.push_back(VE.getValueID(II->getNormalDest())); 2386 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2387 Vals.push_back(getTypeID(FTy)); 2388 pushValueAndType(Callee, InstID, Vals); 2389 2390 // Emit value #'s for the fixed parameters. 2391 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2392 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2393 2394 // Emit type/value pairs for varargs params. 2395 if (FTy->isVarArg()) { 2396 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands() - 3; i != e; 2397 ++i) 2398 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2399 } 2400 break; 2401 } 2402 case Instruction::Resume: 2403 Code = bitc::FUNC_CODE_INST_RESUME; 2404 pushValueAndType(I.getOperand(0), InstID, Vals); 2405 break; 2406 case Instruction::Unreachable: 2407 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2408 AbbrevToUse = (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV; 2409 break; 2410 2411 case Instruction::PHI: { 2412 const PHINode &PN = cast<PHINode>(I); 2413 Code = bitc::FUNC_CODE_INST_PHI; 2414 // With the newer instruction encoding, forward references could give 2415 // negative valued IDs. This is most common for PHIs, so we use 2416 // signed VBRs. 2417 SmallVector<uint64_t, 128> Vals64; 2418 Vals64.push_back(getTypeID(PN.getType())); 2419 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2420 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 2421 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2422 } 2423 // Emit a Vals64 vector and exit. 2424 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2425 Vals64.clear(); 2426 return; 2427 } 2428 2429 case Instruction::LandingPad: { 2430 const LandingPadInst &LP = cast<LandingPadInst>(I); 2431 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2432 Vals.push_back(getTypeID(LP.getType())); 2433 Vals.push_back(LP.isCleanup()); 2434 Vals.push_back(LP.getNumClauses()); 2435 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2436 if (LP.isCatch(I)) 2437 Vals.push_back(LandingPadInst::Catch); 2438 else 2439 Vals.push_back(LandingPadInst::Filter); 2440 pushValueAndType(LP.getClause(I), InstID, Vals); 2441 } 2442 break; 2443 } 2444 2445 case Instruction::Alloca: { 2446 Code = bitc::FUNC_CODE_INST_ALLOCA; 2447 const AllocaInst &AI = cast<AllocaInst>(I); 2448 Vals.push_back(getTypeID(AI.getAllocatedType())); 2449 Vals.push_back(getTypeID(I.getOperand(0)->getType())); 2450 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2451 using APV = AllocaPackedValues; 2452 unsigned Record = 0; 2453 unsigned EncodedAlign = getEncodedAlign(AI.getAlign()); 2454 Bitfield::set<APV::AlignLower>( 2455 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1)); 2456 Bitfield::set<APV::AlignUpper>(Record, 2457 EncodedAlign >> APV::AlignLower::Bits); 2458 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca()); 2459 Vals.push_back(Record); 2460 break; 2461 } 2462 2463 case Instruction::Load: 2464 if (cast<LoadInst>(I).isAtomic()) { 2465 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 2466 pushValueAndType(I.getOperand(0), InstID, Vals); 2467 } else { 2468 Code = bitc::FUNC_CODE_INST_LOAD; 2469 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 2470 AbbrevToUse = (unsigned)FUNCTION_INST_LOAD_ABBREV; 2471 } 2472 Vals.push_back(getTypeID(I.getType())); 2473 Vals.push_back(Log2(cast<LoadInst>(I).getAlign()) + 1); 2474 Vals.push_back(cast<LoadInst>(I).isVolatile()); 2475 if (cast<LoadInst>(I).isAtomic()) { 2476 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 2477 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 2478 } 2479 break; 2480 case Instruction::Store: 2481 if (cast<StoreInst>(I).isAtomic()) 2482 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 2483 else 2484 Code = bitc::FUNC_CODE_INST_STORE; 2485 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 2486 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 2487 Vals.push_back(Log2(cast<StoreInst>(I).getAlign()) + 1); 2488 Vals.push_back(cast<StoreInst>(I).isVolatile()); 2489 if (cast<StoreInst>(I).isAtomic()) { 2490 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 2491 Vals.push_back( 2492 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 2493 } 2494 break; 2495 case Instruction::AtomicCmpXchg: 2496 Code = bitc::FUNC_CODE_INST_CMPXCHG; 2497 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2498 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 2499 pushValue(I.getOperand(2), InstID, Vals); // newval. 2500 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 2501 Vals.push_back( 2502 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 2503 Vals.push_back( 2504 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 2505 Vals.push_back( 2506 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 2507 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 2508 break; 2509 case Instruction::AtomicRMW: 2510 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 2511 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2512 pushValue(I.getOperand(1), InstID, Vals); // val. 2513 Vals.push_back( 2514 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 2515 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 2516 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 2517 Vals.push_back( 2518 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 2519 break; 2520 case Instruction::Fence: 2521 Code = bitc::FUNC_CODE_INST_FENCE; 2522 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 2523 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 2524 break; 2525 case Instruction::Call: { 2526 const CallInst &CI = cast<CallInst>(I); 2527 FunctionType *FTy = CI.getFunctionType(); 2528 2529 Code = bitc::FUNC_CODE_INST_CALL; 2530 2531 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 2532 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) | 2533 unsigned(CI.isMustTailCall()) << 14 | 1 << 15); 2534 Vals.push_back(getTypeID(FTy, CI.getCalledFunction())); 2535 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 2536 2537 // Emit value #'s for the fixed parameters. 2538 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 2539 // Check for labels (can happen with asm labels). 2540 if (FTy->getParamType(i)->isLabelTy()) 2541 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 2542 else 2543 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 2544 } 2545 2546 // Emit type/value pairs for varargs params. 2547 if (FTy->isVarArg()) { 2548 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i) 2549 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 2550 } 2551 break; 2552 } 2553 case Instruction::VAArg: 2554 Code = bitc::FUNC_CODE_INST_VAARG; 2555 Vals.push_back(getTypeID(I.getOperand(0)->getType())); // valistty 2556 pushValue(I.getOperand(0), InstID, Vals); // valist. 2557 Vals.push_back(getTypeID(I.getType())); // restype. 2558 break; 2559 } 2560 2561 Stream.EmitRecord(Code, Vals, AbbrevToUse); 2562 Vals.clear(); 2563 } 2564 2565 // Emit names for globals/functions etc. 2566 void DXILBitcodeWriter::writeFunctionLevelValueSymbolTable( 2567 const ValueSymbolTable &VST) { 2568 if (VST.empty()) 2569 return; 2570 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 2571 2572 SmallVector<unsigned, 64> NameVals; 2573 2574 // HLSL Change 2575 // Read the named values from a sorted list instead of the original list 2576 // to ensure the binary is the same no matter what values ever existed. 2577 SmallVector<const ValueName *, 16> SortedTable; 2578 2579 for (auto &VI : VST) { 2580 SortedTable.push_back(VI.second->getValueName()); 2581 } 2582 // The keys are unique, so there shouldn't be stability issues. 2583 std::sort(SortedTable.begin(), SortedTable.end(), 2584 [](const ValueName *A, const ValueName *B) { 2585 return A->first() < B->first(); 2586 }); 2587 2588 for (const ValueName *SI : SortedTable) { 2589 auto &Name = *SI; 2590 2591 // Figure out the encoding to use for the name. 2592 bool is7Bit = true; 2593 bool isChar6 = true; 2594 for (const char *C = Name.getKeyData(), *E = C + Name.getKeyLength(); 2595 C != E; ++C) { 2596 if (isChar6) 2597 isChar6 = BitCodeAbbrevOp::isChar6(*C); 2598 if ((unsigned char)*C & 128) { 2599 is7Bit = false; 2600 break; // don't bother scanning the rest. 2601 } 2602 } 2603 2604 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 2605 2606 // VST_ENTRY: [valueid, namechar x N] 2607 // VST_BBENTRY: [bbid, namechar x N] 2608 unsigned Code; 2609 if (isa<BasicBlock>(SI->getValue())) { 2610 Code = bitc::VST_CODE_BBENTRY; 2611 if (isChar6) 2612 AbbrevToUse = VST_BBENTRY_6_ABBREV; 2613 } else { 2614 Code = bitc::VST_CODE_ENTRY; 2615 if (isChar6) 2616 AbbrevToUse = VST_ENTRY_6_ABBREV; 2617 else if (is7Bit) 2618 AbbrevToUse = VST_ENTRY_7_ABBREV; 2619 } 2620 2621 NameVals.push_back(VE.getValueID(SI->getValue())); 2622 for (const char *P = Name.getKeyData(), 2623 *E = Name.getKeyData() + Name.getKeyLength(); 2624 P != E; ++P) 2625 NameVals.push_back((unsigned char)*P); 2626 2627 // Emit the finished record. 2628 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 2629 NameVals.clear(); 2630 } 2631 Stream.ExitBlock(); 2632 } 2633 2634 void DXILBitcodeWriter::writeUseList(UseListOrder &&Order) { 2635 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 2636 unsigned Code; 2637 if (isa<BasicBlock>(Order.V)) 2638 Code = bitc::USELIST_CODE_BB; 2639 else 2640 Code = bitc::USELIST_CODE_DEFAULT; 2641 2642 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 2643 Record.push_back(VE.getValueID(Order.V)); 2644 Stream.EmitRecord(Code, Record); 2645 } 2646 2647 void DXILBitcodeWriter::writeUseListBlock(const Function *F) { 2648 auto hasMore = [&]() { 2649 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 2650 }; 2651 if (!hasMore()) 2652 // Nothing to do. 2653 return; 2654 2655 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 2656 while (hasMore()) { 2657 writeUseList(std::move(VE.UseListOrders.back())); 2658 VE.UseListOrders.pop_back(); 2659 } 2660 Stream.ExitBlock(); 2661 } 2662 2663 /// Emit a function body to the module stream. 2664 void DXILBitcodeWriter::writeFunction(const Function &F) { 2665 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 2666 VE.incorporateFunction(F); 2667 2668 SmallVector<unsigned, 64> Vals; 2669 2670 // Emit the number of basic blocks, so the reader can create them ahead of 2671 // time. 2672 Vals.push_back(VE.getBasicBlocks().size()); 2673 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 2674 Vals.clear(); 2675 2676 // If there are function-local constants, emit them now. 2677 unsigned CstStart, CstEnd; 2678 VE.getFunctionConstantRange(CstStart, CstEnd); 2679 writeConstants(CstStart, CstEnd, false); 2680 2681 // If there is function-local metadata, emit it now. 2682 writeFunctionMetadata(F); 2683 2684 // Keep a running idea of what the instruction ID is. 2685 unsigned InstID = CstEnd; 2686 2687 bool NeedsMetadataAttachment = F.hasMetadata(); 2688 2689 DILocation *LastDL = nullptr; 2690 2691 // Finally, emit all the instructions, in order. 2692 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 2693 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 2694 ++I) { 2695 writeInstruction(*I, InstID, Vals); 2696 2697 if (!I->getType()->isVoidTy()) 2698 ++InstID; 2699 2700 // If the instruction has metadata, write a metadata attachment later. 2701 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 2702 2703 // If the instruction has a debug location, emit it. 2704 DILocation *DL = I->getDebugLoc(); 2705 if (!DL) 2706 continue; 2707 2708 if (DL == LastDL) { 2709 // Just repeat the same debug loc as last time. 2710 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 2711 continue; 2712 } 2713 2714 Vals.push_back(DL->getLine()); 2715 Vals.push_back(DL->getColumn()); 2716 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 2717 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 2718 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 2719 Vals.clear(); 2720 2721 LastDL = DL; 2722 } 2723 2724 // Emit names for all the instructions etc. 2725 if (auto *Symtab = F.getValueSymbolTable()) 2726 writeFunctionLevelValueSymbolTable(*Symtab); 2727 2728 if (NeedsMetadataAttachment) 2729 writeFunctionMetadataAttachment(F); 2730 2731 writeUseListBlock(&F); 2732 VE.purgeFunction(); 2733 Stream.ExitBlock(); 2734 } 2735 2736 // Emit blockinfo, which defines the standard abbreviations etc. 2737 void DXILBitcodeWriter::writeBlockInfo() { 2738 // We only want to emit block info records for blocks that have multiple 2739 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 2740 // Other blocks can define their abbrevs inline. 2741 Stream.EnterBlockInfoBlock(); 2742 2743 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. 2744 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 2746 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2749 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2750 std::move(Abbv)) != VST_ENTRY_8_ABBREV) 2751 assert(false && "Unexpected abbrev ordering!"); 2752 } 2753 2754 { // 7-bit fixed width VST_ENTRY strings. 2755 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2756 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2757 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2760 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2761 std::move(Abbv)) != VST_ENTRY_7_ABBREV) 2762 assert(false && "Unexpected abbrev ordering!"); 2763 } 2764 { // 6-bit char6 VST_ENTRY strings. 2765 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2766 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 2767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2770 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2771 std::move(Abbv)) != VST_ENTRY_6_ABBREV) 2772 assert(false && "Unexpected abbrev ordering!"); 2773 } 2774 { // 6-bit char6 VST_BBENTRY strings. 2775 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2776 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 2777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2780 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 2781 std::move(Abbv)) != VST_BBENTRY_6_ABBREV) 2782 assert(false && "Unexpected abbrev ordering!"); 2783 } 2784 2785 { // SETTYPE abbrev for CONSTANTS_BLOCK. 2786 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2787 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 2788 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2789 VE.computeBitsRequiredForTypeIndicies())); 2790 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2791 CONSTANTS_SETTYPE_ABBREV) 2792 assert(false && "Unexpected abbrev ordering!"); 2793 } 2794 2795 { // INTEGER abbrev for CONSTANTS_BLOCK. 2796 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2797 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 2798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 2799 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2800 CONSTANTS_INTEGER_ABBREV) 2801 assert(false && "Unexpected abbrev ordering!"); 2802 } 2803 2804 { // CE_CAST abbrev for CONSTANTS_BLOCK. 2805 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2806 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 2807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 2808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 2809 VE.computeBitsRequiredForTypeIndicies())); 2810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 2811 2812 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2813 CONSTANTS_CE_CAST_Abbrev) 2814 assert(false && "Unexpected abbrev ordering!"); 2815 } 2816 { // NULL abbrev for CONSTANTS_BLOCK. 2817 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2818 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 2819 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) != 2820 CONSTANTS_NULL_Abbrev) 2821 assert(false && "Unexpected abbrev ordering!"); 2822 } 2823 2824 // FIXME: This should only use space for first class types! 2825 2826 { // INST_LOAD abbrev for FUNCTION_BLOCK. 2827 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2828 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 2829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 2830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2831 VE.computeBitsRequiredForTypeIndicies())); 2832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 2833 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 2834 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2835 (unsigned)FUNCTION_INST_LOAD_ABBREV) 2836 assert(false && "Unexpected abbrev ordering!"); 2837 } 2838 { // INST_BINOP abbrev for FUNCTION_BLOCK. 2839 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2840 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2842 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2844 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2845 (unsigned)FUNCTION_INST_BINOP_ABBREV) 2846 assert(false && "Unexpected abbrev ordering!"); 2847 } 2848 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 2849 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2850 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 2851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 2852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 2853 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2854 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 2855 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2856 (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV) 2857 assert(false && "Unexpected abbrev ordering!"); 2858 } 2859 { // INST_CAST abbrev for FUNCTION_BLOCK. 2860 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2861 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 2862 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 2863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2864 VE.computeBitsRequiredForTypeIndicies())); 2865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 2866 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2867 (unsigned)FUNCTION_INST_CAST_ABBREV) 2868 assert(false && "Unexpected abbrev ordering!"); 2869 } 2870 2871 { // INST_RET abbrev for FUNCTION_BLOCK. 2872 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2873 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2874 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2875 (unsigned)FUNCTION_INST_RET_VOID_ABBREV) 2876 assert(false && "Unexpected abbrev ordering!"); 2877 } 2878 { // INST_RET abbrev for FUNCTION_BLOCK. 2879 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2880 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 2881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 2882 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2883 (unsigned)FUNCTION_INST_RET_VAL_ABBREV) 2884 assert(false && "Unexpected abbrev ordering!"); 2885 } 2886 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 2887 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2888 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 2889 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2890 (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV) 2891 assert(false && "Unexpected abbrev ordering!"); 2892 } 2893 { 2894 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2895 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 2896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 2897 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 2898 Log2_32_Ceil(VE.getTypes().size() + 1))); 2899 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2900 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2901 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) != 2902 (unsigned)FUNCTION_INST_GEP_ABBREV) 2903 assert(false && "Unexpected abbrev ordering!"); 2904 } 2905 2906 Stream.ExitBlock(); 2907 } 2908 2909 void DXILBitcodeWriter::writeModuleVersion() { 2910 // VERSION: [version#] 2911 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<unsigned>{1}); 2912 } 2913 2914 /// WriteModule - Emit the specified module to the bitstream. 2915 void DXILBitcodeWriter::write() { 2916 // The identification block is new since llvm-3.7, but the old bitcode reader 2917 // will skip it. 2918 // writeIdentificationBlock(Stream); 2919 2920 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 2921 2922 // It is redundant to fully-specify this here, but nice to make it explicit 2923 // so that it is clear the DXIL module version is different. 2924 DXILBitcodeWriter::writeModuleVersion(); 2925 2926 // Emit blockinfo, which defines the standard abbreviations etc. 2927 writeBlockInfo(); 2928 2929 // Emit information about attribute groups. 2930 writeAttributeGroupTable(); 2931 2932 // Emit information about parameter attributes. 2933 writeAttributeTable(); 2934 2935 // Emit information describing all of the types in the module. 2936 writeTypeTable(); 2937 2938 writeComdats(); 2939 2940 // Emit top-level description of module, including target triple, inline asm, 2941 // descriptors for global variables, and function prototype info. 2942 writeModuleInfo(); 2943 2944 // Emit constants. 2945 writeModuleConstants(); 2946 2947 // Emit metadata. 2948 writeModuleMetadataKinds(); 2949 2950 // Emit metadata. 2951 writeModuleMetadata(); 2952 2953 // Emit names for globals/functions etc. 2954 // DXIL uses the same format for module-level value symbol table as for the 2955 // function level table. 2956 writeFunctionLevelValueSymbolTable(M.getValueSymbolTable()); 2957 2958 // Emit module-level use-lists. 2959 writeUseListBlock(nullptr); 2960 2961 // Emit function bodies. 2962 for (const Function &F : M) 2963 if (!F.isDeclaration()) 2964 writeFunction(F); 2965 2966 Stream.ExitBlock(); 2967 } 2968