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