1 //===- Bitcode/Writer/BitcodeWriter.cpp - 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 "llvm/Bitcode/BitcodeWriter.h" 14 #include "ValueEnumerator.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/ADT/Triple.h" 27 #include "llvm/Bitcode/BitcodeReader.h" 28 #include "llvm/Bitcode/LLVMBitCodes.h" 29 #include "llvm/Bitstream/BitCodes.h" 30 #include "llvm/Bitstream/BitstreamWriter.h" 31 #include "llvm/Config/llvm-config.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/Comdat.h" 35 #include "llvm/IR/Constant.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/DebugInfoMetadata.h" 38 #include "llvm/IR/DebugLoc.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalIFunc.h" 43 #include "llvm/IR/GlobalObject.h" 44 #include "llvm/IR/GlobalValue.h" 45 #include "llvm/IR/GlobalVariable.h" 46 #include "llvm/IR/InlineAsm.h" 47 #include "llvm/IR/InstrTypes.h" 48 #include "llvm/IR/Instruction.h" 49 #include "llvm/IR/Instructions.h" 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/ModuleSummaryIndex.h" 54 #include "llvm/IR/Operator.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/IR/UseListOrder.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/IR/ValueSymbolTable.h" 59 #include "llvm/MC/StringTableBuilder.h" 60 #include "llvm/Object/IRSymtab.h" 61 #include "llvm/Support/AtomicOrdering.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Endian.h" 65 #include "llvm/Support/Error.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/SHA1.h" 69 #include "llvm/Support/TargetRegistry.h" 70 #include "llvm/Support/raw_ostream.h" 71 #include <algorithm> 72 #include <cassert> 73 #include <cstddef> 74 #include <cstdint> 75 #include <iterator> 76 #include <map> 77 #include <memory> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 static cl::opt<unsigned> 85 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), 86 cl::desc("Number of metadatas above which we emit an index " 87 "to enable lazy-loading")); 88 89 static cl::opt<bool> WriteRelBFToSummary( 90 "write-relbf-to-summary", cl::Hidden, cl::init(false), 91 cl::desc("Write relative block frequency to function summary ")); 92 93 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold; 94 95 namespace { 96 97 /// These are manifest constants used by the bitcode writer. They do not need to 98 /// be kept in sync with the reader, but need to be consistent within this file. 99 enum { 100 // VALUE_SYMTAB_BLOCK abbrev id's. 101 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 102 VST_ENTRY_7_ABBREV, 103 VST_ENTRY_6_ABBREV, 104 VST_BBENTRY_6_ABBREV, 105 106 // CONSTANTS_BLOCK abbrev id's. 107 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 108 CONSTANTS_INTEGER_ABBREV, 109 CONSTANTS_CE_CAST_Abbrev, 110 CONSTANTS_NULL_Abbrev, 111 112 // FUNCTION_BLOCK abbrev id's. 113 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 114 FUNCTION_INST_UNOP_ABBREV, 115 FUNCTION_INST_UNOP_FLAGS_ABBREV, 116 FUNCTION_INST_BINOP_ABBREV, 117 FUNCTION_INST_BINOP_FLAGS_ABBREV, 118 FUNCTION_INST_CAST_ABBREV, 119 FUNCTION_INST_RET_VOID_ABBREV, 120 FUNCTION_INST_RET_VAL_ABBREV, 121 FUNCTION_INST_UNREACHABLE_ABBREV, 122 FUNCTION_INST_GEP_ABBREV, 123 }; 124 125 /// Abstract class to manage the bitcode writing, subclassed for each bitcode 126 /// file type. 127 class BitcodeWriterBase { 128 protected: 129 /// The stream created and owned by the client. 130 BitstreamWriter &Stream; 131 132 StringTableBuilder &StrtabBuilder; 133 134 public: 135 /// Constructs a BitcodeWriterBase object that writes to the provided 136 /// \p Stream. 137 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder) 138 : Stream(Stream), StrtabBuilder(StrtabBuilder) {} 139 140 protected: 141 void writeBitcodeHeader(); 142 void writeModuleVersion(); 143 }; 144 145 void BitcodeWriterBase::writeModuleVersion() { 146 // VERSION: [version#] 147 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2}); 148 } 149 150 /// Base class to manage the module bitcode writing, currently subclassed for 151 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter. 152 class ModuleBitcodeWriterBase : public BitcodeWriterBase { 153 protected: 154 /// The Module to write to bitcode. 155 const Module &M; 156 157 /// Enumerates ids for all values in the module. 158 ValueEnumerator VE; 159 160 /// Optional per-module index to write for ThinLTO. 161 const ModuleSummaryIndex *Index; 162 163 /// Map that holds the correspondence between GUIDs in the summary index, 164 /// that came from indirect call profiles, and a value id generated by this 165 /// class to use in the VST and summary block records. 166 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 167 168 /// Tracks the last value id recorded in the GUIDToValueMap. 169 unsigned GlobalValueId; 170 171 /// Saves the offset of the VSTOffset record that must eventually be 172 /// backpatched with the offset of the actual VST. 173 uint64_t VSTOffsetPlaceholder = 0; 174 175 public: 176 /// Constructs a ModuleBitcodeWriterBase object for the given Module, 177 /// writing to the provided \p Buffer. 178 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder, 179 BitstreamWriter &Stream, 180 bool ShouldPreserveUseListOrder, 181 const ModuleSummaryIndex *Index) 182 : BitcodeWriterBase(Stream, StrtabBuilder), M(M), 183 VE(M, ShouldPreserveUseListOrder), Index(Index) { 184 // Assign ValueIds to any callee values in the index that came from 185 // indirect call profiles and were recorded as a GUID not a Value* 186 // (which would have been assigned an ID by the ValueEnumerator). 187 // The starting ValueId is just after the number of values in the 188 // ValueEnumerator, so that they can be emitted in the VST. 189 GlobalValueId = VE.getValues().size(); 190 if (!Index) 191 return; 192 for (const auto &GUIDSummaryLists : *Index) 193 // Examine all summaries for this GUID. 194 for (auto &Summary : GUIDSummaryLists.second.SummaryList) 195 if (auto FS = dyn_cast<FunctionSummary>(Summary.get())) 196 // For each call in the function summary, see if the call 197 // is to a GUID (which means it is for an indirect call, 198 // otherwise we would have a Value for it). If so, synthesize 199 // a value id. 200 for (auto &CallEdge : FS->calls()) 201 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue()) 202 assignValueId(CallEdge.first.getGUID()); 203 } 204 205 protected: 206 void writePerModuleGlobalValueSummary(); 207 208 private: 209 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 210 GlobalValueSummary *Summary, 211 unsigned ValueID, 212 unsigned FSCallsAbbrev, 213 unsigned FSCallsProfileAbbrev, 214 const Function &F); 215 void writeModuleLevelReferences(const GlobalVariable &V, 216 SmallVector<uint64_t, 64> &NameVals, 217 unsigned FSModRefsAbbrev, 218 unsigned FSModVTableRefsAbbrev); 219 220 void assignValueId(GlobalValue::GUID ValGUID) { 221 GUIDToValueIdMap[ValGUID] = ++GlobalValueId; 222 } 223 224 unsigned getValueId(GlobalValue::GUID ValGUID) { 225 const auto &VMI = GUIDToValueIdMap.find(ValGUID); 226 // Expect that any GUID value had a value Id assigned by an 227 // earlier call to assignValueId. 228 assert(VMI != GUIDToValueIdMap.end() && 229 "GUID does not have assigned value Id"); 230 return VMI->second; 231 } 232 233 // Helper to get the valueId for the type of value recorded in VI. 234 unsigned getValueId(ValueInfo VI) { 235 if (!VI.haveGVs() || !VI.getValue()) 236 return getValueId(VI.getGUID()); 237 return VE.getValueID(VI.getValue()); 238 } 239 240 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 241 }; 242 243 /// Class to manage the bitcode writing for a module. 244 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase { 245 /// Pointer to the buffer allocated by caller for bitcode writing. 246 const SmallVectorImpl<char> &Buffer; 247 248 /// True if a module hash record should be written. 249 bool GenerateHash; 250 251 /// If non-null, when GenerateHash is true, the resulting hash is written 252 /// into ModHash. 253 ModuleHash *ModHash; 254 255 SHA1 Hasher; 256 257 /// The start bit of the identification block. 258 uint64_t BitcodeStartBit; 259 260 public: 261 /// Constructs a ModuleBitcodeWriter object for the given Module, 262 /// writing to the provided \p Buffer. 263 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer, 264 StringTableBuilder &StrtabBuilder, 265 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder, 266 const ModuleSummaryIndex *Index, bool GenerateHash, 267 ModuleHash *ModHash = nullptr) 268 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 269 ShouldPreserveUseListOrder, Index), 270 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash), 271 BitcodeStartBit(Stream.GetCurrentBitNo()) {} 272 273 /// Emit the current module to the bitstream. 274 void write(); 275 276 private: 277 uint64_t bitcodeStartBit() { return BitcodeStartBit; } 278 279 size_t addToStrtab(StringRef Str); 280 281 void writeAttributeGroupTable(); 282 void writeAttributeTable(); 283 void writeTypeTable(); 284 void writeComdats(); 285 void writeValueSymbolTableForwardDecl(); 286 void writeModuleInfo(); 287 void writeValueAsMetadata(const ValueAsMetadata *MD, 288 SmallVectorImpl<uint64_t> &Record); 289 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record, 290 unsigned Abbrev); 291 unsigned createDILocationAbbrev(); 292 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record, 293 unsigned &Abbrev); 294 unsigned createGenericDINodeAbbrev(); 295 void writeGenericDINode(const GenericDINode *N, 296 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev); 297 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record, 298 unsigned Abbrev); 299 void writeDIEnumerator(const DIEnumerator *N, 300 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 301 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record, 302 unsigned Abbrev); 303 void writeDIDerivedType(const DIDerivedType *N, 304 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 305 void writeDICompositeType(const DICompositeType *N, 306 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 307 void writeDISubroutineType(const DISubroutineType *N, 308 SmallVectorImpl<uint64_t> &Record, 309 unsigned Abbrev); 310 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record, 311 unsigned Abbrev); 312 void writeDICompileUnit(const DICompileUnit *N, 313 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 314 void writeDISubprogram(const DISubprogram *N, 315 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 316 void writeDILexicalBlock(const DILexicalBlock *N, 317 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 318 void writeDILexicalBlockFile(const DILexicalBlockFile *N, 319 SmallVectorImpl<uint64_t> &Record, 320 unsigned Abbrev); 321 void writeDICommonBlock(const DICommonBlock *N, 322 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 323 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record, 324 unsigned Abbrev); 325 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record, 326 unsigned Abbrev); 327 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record, 328 unsigned Abbrev); 329 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record, 330 unsigned Abbrev); 331 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N, 332 SmallVectorImpl<uint64_t> &Record, 333 unsigned Abbrev); 334 void writeDITemplateValueParameter(const DITemplateValueParameter *N, 335 SmallVectorImpl<uint64_t> &Record, 336 unsigned Abbrev); 337 void writeDIGlobalVariable(const DIGlobalVariable *N, 338 SmallVectorImpl<uint64_t> &Record, 339 unsigned Abbrev); 340 void writeDILocalVariable(const DILocalVariable *N, 341 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 342 void writeDILabel(const DILabel *N, 343 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 344 void writeDIExpression(const DIExpression *N, 345 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 346 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N, 347 SmallVectorImpl<uint64_t> &Record, 348 unsigned Abbrev); 349 void writeDIObjCProperty(const DIObjCProperty *N, 350 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev); 351 void writeDIImportedEntity(const DIImportedEntity *N, 352 SmallVectorImpl<uint64_t> &Record, 353 unsigned Abbrev); 354 unsigned createNamedMetadataAbbrev(); 355 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record); 356 unsigned createMetadataStringsAbbrev(); 357 void writeMetadataStrings(ArrayRef<const Metadata *> Strings, 358 SmallVectorImpl<uint64_t> &Record); 359 void writeMetadataRecords(ArrayRef<const Metadata *> MDs, 360 SmallVectorImpl<uint64_t> &Record, 361 std::vector<unsigned> *MDAbbrevs = nullptr, 362 std::vector<uint64_t> *IndexPos = nullptr); 363 void writeModuleMetadata(); 364 void writeFunctionMetadata(const Function &F); 365 void writeFunctionMetadataAttachment(const Function &F); 366 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV); 367 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record, 368 const GlobalObject &GO); 369 void writeModuleMetadataKinds(); 370 void writeOperandBundleTags(); 371 void writeSyncScopeNames(); 372 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal); 373 void writeModuleConstants(); 374 bool pushValueAndType(const Value *V, unsigned InstID, 375 SmallVectorImpl<unsigned> &Vals); 376 void writeOperandBundles(const CallBase &CB, unsigned InstID); 377 void pushValue(const Value *V, unsigned InstID, 378 SmallVectorImpl<unsigned> &Vals); 379 void pushValueSigned(const Value *V, unsigned InstID, 380 SmallVectorImpl<uint64_t> &Vals); 381 void writeInstruction(const Instruction &I, unsigned InstID, 382 SmallVectorImpl<unsigned> &Vals); 383 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST); 384 void writeGlobalValueSymbolTable( 385 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 386 void writeUseList(UseListOrder &&Order); 387 void writeUseListBlock(const Function *F); 388 void 389 writeFunction(const Function &F, 390 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex); 391 void writeBlockInfo(); 392 void writeModuleHash(size_t BlockStartPos); 393 394 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { 395 return unsigned(SSID); 396 } 397 }; 398 399 /// Class to manage the bitcode writing for a combined index. 400 class IndexBitcodeWriter : public BitcodeWriterBase { 401 /// The combined index to write to bitcode. 402 const ModuleSummaryIndex &Index; 403 404 /// When writing a subset of the index for distributed backends, client 405 /// provides a map of modules to the corresponding GUIDs/summaries to write. 406 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex; 407 408 /// Map that holds the correspondence between the GUID used in the combined 409 /// index and a value id generated by this class to use in references. 410 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap; 411 412 /// Tracks the last value id recorded in the GUIDToValueMap. 413 unsigned GlobalValueId = 0; 414 415 public: 416 /// Constructs a IndexBitcodeWriter object for the given combined index, 417 /// writing to the provided \p Buffer. When writing a subset of the index 418 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map. 419 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder, 420 const ModuleSummaryIndex &Index, 421 const std::map<std::string, GVSummaryMapTy> 422 *ModuleToSummariesForIndex = nullptr) 423 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index), 424 ModuleToSummariesForIndex(ModuleToSummariesForIndex) { 425 // Assign unique value ids to all summaries to be written, for use 426 // in writing out the call graph edges. Save the mapping from GUID 427 // to the new global value id to use when writing those edges, which 428 // are currently saved in the index in terms of GUID. 429 forEachSummary([&](GVInfo I, bool) { 430 GUIDToValueIdMap[I.first] = ++GlobalValueId; 431 }); 432 } 433 434 /// The below iterator returns the GUID and associated summary. 435 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>; 436 437 /// Calls the callback for each value GUID and summary to be written to 438 /// bitcode. This hides the details of whether they are being pulled from the 439 /// entire index or just those in a provided ModuleToSummariesForIndex map. 440 template<typename Functor> 441 void forEachSummary(Functor Callback) { 442 if (ModuleToSummariesForIndex) { 443 for (auto &M : *ModuleToSummariesForIndex) 444 for (auto &Summary : M.second) { 445 Callback(Summary, false); 446 // Ensure aliasee is handled, e.g. for assigning a valueId, 447 // even if we are not importing the aliasee directly (the 448 // imported alias will contain a copy of aliasee). 449 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond())) 450 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true); 451 } 452 } else { 453 for (auto &Summaries : Index) 454 for (auto &Summary : Summaries.second.SummaryList) 455 Callback({Summaries.first, Summary.get()}, false); 456 } 457 } 458 459 /// Calls the callback for each entry in the modulePaths StringMap that 460 /// should be written to the module path string table. This hides the details 461 /// of whether they are being pulled from the entire index or just those in a 462 /// provided ModuleToSummariesForIndex map. 463 template <typename Functor> void forEachModule(Functor Callback) { 464 if (ModuleToSummariesForIndex) { 465 for (const auto &M : *ModuleToSummariesForIndex) { 466 const auto &MPI = Index.modulePaths().find(M.first); 467 if (MPI == Index.modulePaths().end()) { 468 // This should only happen if the bitcode file was empty, in which 469 // case we shouldn't be importing (the ModuleToSummariesForIndex 470 // would only include the module we are writing and index for). 471 assert(ModuleToSummariesForIndex->size() == 1); 472 continue; 473 } 474 Callback(*MPI); 475 } 476 } else { 477 for (const auto &MPSE : Index.modulePaths()) 478 Callback(MPSE); 479 } 480 } 481 482 /// Main entry point for writing a combined index to bitcode. 483 void write(); 484 485 private: 486 void writeModStrings(); 487 void writeCombinedGlobalValueSummary(); 488 489 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) { 490 auto VMI = GUIDToValueIdMap.find(ValGUID); 491 if (VMI == GUIDToValueIdMap.end()) 492 return None; 493 return VMI->second; 494 } 495 496 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; } 497 }; 498 499 } // end anonymous namespace 500 501 static unsigned getEncodedCastOpcode(unsigned Opcode) { 502 switch (Opcode) { 503 default: llvm_unreachable("Unknown cast instruction!"); 504 case Instruction::Trunc : return bitc::CAST_TRUNC; 505 case Instruction::ZExt : return bitc::CAST_ZEXT; 506 case Instruction::SExt : return bitc::CAST_SEXT; 507 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 508 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 509 case Instruction::UIToFP : return bitc::CAST_UITOFP; 510 case Instruction::SIToFP : return bitc::CAST_SITOFP; 511 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 512 case Instruction::FPExt : return bitc::CAST_FPEXT; 513 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 514 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 515 case Instruction::BitCast : return bitc::CAST_BITCAST; 516 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST; 517 } 518 } 519 520 static unsigned getEncodedUnaryOpcode(unsigned Opcode) { 521 switch (Opcode) { 522 default: llvm_unreachable("Unknown binary instruction!"); 523 case Instruction::FNeg: return bitc::UNOP_FNEG; 524 } 525 } 526 527 static unsigned getEncodedBinaryOpcode(unsigned Opcode) { 528 switch (Opcode) { 529 default: llvm_unreachable("Unknown binary instruction!"); 530 case Instruction::Add: 531 case Instruction::FAdd: return bitc::BINOP_ADD; 532 case Instruction::Sub: 533 case Instruction::FSub: return bitc::BINOP_SUB; 534 case Instruction::Mul: 535 case Instruction::FMul: return bitc::BINOP_MUL; 536 case Instruction::UDiv: return bitc::BINOP_UDIV; 537 case Instruction::FDiv: 538 case Instruction::SDiv: return bitc::BINOP_SDIV; 539 case Instruction::URem: return bitc::BINOP_UREM; 540 case Instruction::FRem: 541 case Instruction::SRem: return bitc::BINOP_SREM; 542 case Instruction::Shl: return bitc::BINOP_SHL; 543 case Instruction::LShr: return bitc::BINOP_LSHR; 544 case Instruction::AShr: return bitc::BINOP_ASHR; 545 case Instruction::And: return bitc::BINOP_AND; 546 case Instruction::Or: return bitc::BINOP_OR; 547 case Instruction::Xor: return bitc::BINOP_XOR; 548 } 549 } 550 551 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 552 switch (Op) { 553 default: llvm_unreachable("Unknown RMW operation!"); 554 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 555 case AtomicRMWInst::Add: return bitc::RMW_ADD; 556 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 557 case AtomicRMWInst::And: return bitc::RMW_AND; 558 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 559 case AtomicRMWInst::Or: return bitc::RMW_OR; 560 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 561 case AtomicRMWInst::Max: return bitc::RMW_MAX; 562 case AtomicRMWInst::Min: return bitc::RMW_MIN; 563 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 564 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 565 case AtomicRMWInst::FAdd: return bitc::RMW_FADD; 566 case AtomicRMWInst::FSub: return bitc::RMW_FSUB; 567 } 568 } 569 570 static unsigned getEncodedOrdering(AtomicOrdering Ordering) { 571 switch (Ordering) { 572 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC; 573 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED; 574 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC; 575 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE; 576 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE; 577 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL; 578 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST; 579 } 580 llvm_unreachable("Invalid ordering"); 581 } 582 583 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, 584 StringRef Str, unsigned AbbrevToUse) { 585 SmallVector<unsigned, 64> Vals; 586 587 // Code: [strchar x N] 588 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 589 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 590 AbbrevToUse = 0; 591 Vals.push_back(Str[i]); 592 } 593 594 // Emit the finished record. 595 Stream.EmitRecord(Code, Vals, AbbrevToUse); 596 } 597 598 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) { 599 switch (Kind) { 600 case Attribute::Alignment: 601 return bitc::ATTR_KIND_ALIGNMENT; 602 case Attribute::AllocSize: 603 return bitc::ATTR_KIND_ALLOC_SIZE; 604 case Attribute::AlwaysInline: 605 return bitc::ATTR_KIND_ALWAYS_INLINE; 606 case Attribute::ArgMemOnly: 607 return bitc::ATTR_KIND_ARGMEMONLY; 608 case Attribute::Builtin: 609 return bitc::ATTR_KIND_BUILTIN; 610 case Attribute::ByVal: 611 return bitc::ATTR_KIND_BY_VAL; 612 case Attribute::Convergent: 613 return bitc::ATTR_KIND_CONVERGENT; 614 case Attribute::InAlloca: 615 return bitc::ATTR_KIND_IN_ALLOCA; 616 case Attribute::Cold: 617 return bitc::ATTR_KIND_COLD; 618 case Attribute::InaccessibleMemOnly: 619 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY; 620 case Attribute::InaccessibleMemOrArgMemOnly: 621 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY; 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::NoFree: 643 return bitc::ATTR_KIND_NOFREE; 644 case Attribute::NoImplicitFloat: 645 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT; 646 case Attribute::NoInline: 647 return bitc::ATTR_KIND_NO_INLINE; 648 case Attribute::NoRecurse: 649 return bitc::ATTR_KIND_NO_RECURSE; 650 case Attribute::NoMerge: 651 return bitc::ATTR_KIND_NO_MERGE; 652 case Attribute::NonLazyBind: 653 return bitc::ATTR_KIND_NON_LAZY_BIND; 654 case Attribute::NonNull: 655 return bitc::ATTR_KIND_NON_NULL; 656 case Attribute::Dereferenceable: 657 return bitc::ATTR_KIND_DEREFERENCEABLE; 658 case Attribute::DereferenceableOrNull: 659 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL; 660 case Attribute::NoRedZone: 661 return bitc::ATTR_KIND_NO_RED_ZONE; 662 case Attribute::NoReturn: 663 return bitc::ATTR_KIND_NO_RETURN; 664 case Attribute::NoSync: 665 return bitc::ATTR_KIND_NOSYNC; 666 case Attribute::NoCfCheck: 667 return bitc::ATTR_KIND_NOCF_CHECK; 668 case Attribute::NoUnwind: 669 return bitc::ATTR_KIND_NO_UNWIND; 670 case Attribute::OptForFuzzing: 671 return bitc::ATTR_KIND_OPT_FOR_FUZZING; 672 case Attribute::OptimizeForSize: 673 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE; 674 case Attribute::OptimizeNone: 675 return bitc::ATTR_KIND_OPTIMIZE_NONE; 676 case Attribute::ReadNone: 677 return bitc::ATTR_KIND_READ_NONE; 678 case Attribute::ReadOnly: 679 return bitc::ATTR_KIND_READ_ONLY; 680 case Attribute::Returned: 681 return bitc::ATTR_KIND_RETURNED; 682 case Attribute::ReturnsTwice: 683 return bitc::ATTR_KIND_RETURNS_TWICE; 684 case Attribute::SExt: 685 return bitc::ATTR_KIND_S_EXT; 686 case Attribute::Speculatable: 687 return bitc::ATTR_KIND_SPECULATABLE; 688 case Attribute::StackAlignment: 689 return bitc::ATTR_KIND_STACK_ALIGNMENT; 690 case Attribute::StackProtect: 691 return bitc::ATTR_KIND_STACK_PROTECT; 692 case Attribute::StackProtectReq: 693 return bitc::ATTR_KIND_STACK_PROTECT_REQ; 694 case Attribute::StackProtectStrong: 695 return bitc::ATTR_KIND_STACK_PROTECT_STRONG; 696 case Attribute::SafeStack: 697 return bitc::ATTR_KIND_SAFESTACK; 698 case Attribute::ShadowCallStack: 699 return bitc::ATTR_KIND_SHADOWCALLSTACK; 700 case Attribute::StrictFP: 701 return bitc::ATTR_KIND_STRICT_FP; 702 case Attribute::StructRet: 703 return bitc::ATTR_KIND_STRUCT_RET; 704 case Attribute::SanitizeAddress: 705 return bitc::ATTR_KIND_SANITIZE_ADDRESS; 706 case Attribute::SanitizeHWAddress: 707 return bitc::ATTR_KIND_SANITIZE_HWADDRESS; 708 case Attribute::SanitizeThread: 709 return bitc::ATTR_KIND_SANITIZE_THREAD; 710 case Attribute::SanitizeMemory: 711 return bitc::ATTR_KIND_SANITIZE_MEMORY; 712 case Attribute::SpeculativeLoadHardening: 713 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING; 714 case Attribute::SwiftError: 715 return bitc::ATTR_KIND_SWIFT_ERROR; 716 case Attribute::SwiftSelf: 717 return bitc::ATTR_KIND_SWIFT_SELF; 718 case Attribute::UWTable: 719 return bitc::ATTR_KIND_UW_TABLE; 720 case Attribute::WillReturn: 721 return bitc::ATTR_KIND_WILLRETURN; 722 case Attribute::WriteOnly: 723 return bitc::ATTR_KIND_WRITEONLY; 724 case Attribute::ZExt: 725 return bitc::ATTR_KIND_Z_EXT; 726 case Attribute::ImmArg: 727 return bitc::ATTR_KIND_IMMARG; 728 case Attribute::SanitizeMemTag: 729 return bitc::ATTR_KIND_SANITIZE_MEMTAG; 730 case Attribute::Preallocated: 731 return bitc::ATTR_KIND_PREALLOCATED; 732 case Attribute::EndAttrKinds: 733 llvm_unreachable("Can not encode end-attribute kinds marker."); 734 case Attribute::None: 735 llvm_unreachable("Can not encode none-attribute."); 736 case Attribute::EmptyKey: 737 case Attribute::TombstoneKey: 738 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey"); 739 } 740 741 llvm_unreachable("Trying to encode unknown attribute"); 742 } 743 744 void ModuleBitcodeWriter::writeAttributeGroupTable() { 745 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps = 746 VE.getAttributeGroups(); 747 if (AttrGrps.empty()) return; 748 749 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3); 750 751 SmallVector<uint64_t, 64> Record; 752 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) { 753 unsigned AttrListIndex = Pair.first; 754 AttributeSet AS = Pair.second; 755 Record.push_back(VE.getAttributeGroupID(Pair)); 756 Record.push_back(AttrListIndex); 757 758 for (Attribute Attr : AS) { 759 if (Attr.isEnumAttribute()) { 760 Record.push_back(0); 761 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 762 } else if (Attr.isIntAttribute()) { 763 Record.push_back(1); 764 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 765 Record.push_back(Attr.getValueAsInt()); 766 } else if (Attr.isStringAttribute()) { 767 StringRef Kind = Attr.getKindAsString(); 768 StringRef Val = Attr.getValueAsString(); 769 770 Record.push_back(Val.empty() ? 3 : 4); 771 Record.append(Kind.begin(), Kind.end()); 772 Record.push_back(0); 773 if (!Val.empty()) { 774 Record.append(Val.begin(), Val.end()); 775 Record.push_back(0); 776 } 777 } else { 778 assert(Attr.isTypeAttribute()); 779 Type *Ty = Attr.getValueAsType(); 780 Record.push_back(Ty ? 6 : 5); 781 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum())); 782 if (Ty) 783 Record.push_back(VE.getTypeID(Attr.getValueAsType())); 784 } 785 } 786 787 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record); 788 Record.clear(); 789 } 790 791 Stream.ExitBlock(); 792 } 793 794 void ModuleBitcodeWriter::writeAttributeTable() { 795 const std::vector<AttributeList> &Attrs = VE.getAttributeLists(); 796 if (Attrs.empty()) return; 797 798 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 799 800 SmallVector<uint64_t, 64> Record; 801 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 802 AttributeList AL = Attrs[i]; 803 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) { 804 AttributeSet AS = AL.getAttributes(i); 805 if (AS.hasAttributes()) 806 Record.push_back(VE.getAttributeGroupID({i, AS})); 807 } 808 809 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 810 Record.clear(); 811 } 812 813 Stream.ExitBlock(); 814 } 815 816 /// WriteTypeTable - Write out the type table for a module. 817 void ModuleBitcodeWriter::writeTypeTable() { 818 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 819 820 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 821 SmallVector<uint64_t, 64> TypeVals; 822 823 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies(); 824 825 // Abbrev for TYPE_CODE_POINTER. 826 auto Abbv = std::make_shared<BitCodeAbbrev>(); 827 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 829 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 830 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 831 832 // Abbrev for TYPE_CODE_FUNCTION. 833 Abbv = std::make_shared<BitCodeAbbrev>(); 834 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 835 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 836 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 837 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 838 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 839 840 // Abbrev for TYPE_CODE_STRUCT_ANON. 841 Abbv = std::make_shared<BitCodeAbbrev>(); 842 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 844 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 845 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 846 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 847 848 // Abbrev for TYPE_CODE_STRUCT_NAME. 849 Abbv = std::make_shared<BitCodeAbbrev>(); 850 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 853 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 854 855 // Abbrev for TYPE_CODE_STRUCT_NAMED. 856 Abbv = std::make_shared<BitCodeAbbrev>(); 857 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 859 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 860 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 861 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 862 863 // Abbrev for TYPE_CODE_ARRAY. 864 Abbv = std::make_shared<BitCodeAbbrev>(); 865 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 866 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 867 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 868 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 869 870 // Emit an entry count so the reader can reserve space. 871 TypeVals.push_back(TypeList.size()); 872 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 873 TypeVals.clear(); 874 875 // Loop over all of the types, emitting each in turn. 876 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 877 Type *T = TypeList[i]; 878 int AbbrevToUse = 0; 879 unsigned Code = 0; 880 881 switch (T->getTypeID()) { 882 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 883 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 884 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 885 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 886 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 887 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 888 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 889 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 890 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 891 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 892 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break; 893 case Type::IntegerTyID: 894 // INTEGER: [width] 895 Code = bitc::TYPE_CODE_INTEGER; 896 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 897 break; 898 case Type::PointerTyID: { 899 PointerType *PTy = cast<PointerType>(T); 900 // POINTER: [pointee type, address space] 901 Code = bitc::TYPE_CODE_POINTER; 902 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 903 unsigned AddressSpace = PTy->getAddressSpace(); 904 TypeVals.push_back(AddressSpace); 905 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 906 break; 907 } 908 case Type::FunctionTyID: { 909 FunctionType *FT = cast<FunctionType>(T); 910 // FUNCTION: [isvararg, retty, paramty x N] 911 Code = bitc::TYPE_CODE_FUNCTION; 912 TypeVals.push_back(FT->isVarArg()); 913 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 914 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 915 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 916 AbbrevToUse = FunctionAbbrev; 917 break; 918 } 919 case Type::StructTyID: { 920 StructType *ST = cast<StructType>(T); 921 // STRUCT: [ispacked, eltty x N] 922 TypeVals.push_back(ST->isPacked()); 923 // Output all of the element types. 924 for (StructType::element_iterator I = ST->element_begin(), 925 E = ST->element_end(); I != E; ++I) 926 TypeVals.push_back(VE.getTypeID(*I)); 927 928 if (ST->isLiteral()) { 929 Code = bitc::TYPE_CODE_STRUCT_ANON; 930 AbbrevToUse = StructAnonAbbrev; 931 } else { 932 if (ST->isOpaque()) { 933 Code = bitc::TYPE_CODE_OPAQUE; 934 } else { 935 Code = bitc::TYPE_CODE_STRUCT_NAMED; 936 AbbrevToUse = StructNamedAbbrev; 937 } 938 939 // Emit the name if it is present. 940 if (!ST->getName().empty()) 941 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 942 StructNameAbbrev); 943 } 944 break; 945 } 946 case Type::ArrayTyID: { 947 ArrayType *AT = cast<ArrayType>(T); 948 // ARRAY: [numelts, eltty] 949 Code = bitc::TYPE_CODE_ARRAY; 950 TypeVals.push_back(AT->getNumElements()); 951 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 952 AbbrevToUse = ArrayAbbrev; 953 break; 954 } 955 case Type::FixedVectorTyID: 956 case Type::ScalableVectorTyID: { 957 VectorType *VT = cast<VectorType>(T); 958 // VECTOR [numelts, eltty] or 959 // [numelts, eltty, scalable] 960 Code = bitc::TYPE_CODE_VECTOR; 961 TypeVals.push_back(VT->getNumElements()); 962 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 963 if (isa<ScalableVectorType>(VT)) 964 TypeVals.push_back(true); 965 break; 966 } 967 } 968 969 // Emit the finished record. 970 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 971 TypeVals.clear(); 972 } 973 974 Stream.ExitBlock(); 975 } 976 977 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) { 978 switch (Linkage) { 979 case GlobalValue::ExternalLinkage: 980 return 0; 981 case GlobalValue::WeakAnyLinkage: 982 return 16; 983 case GlobalValue::AppendingLinkage: 984 return 2; 985 case GlobalValue::InternalLinkage: 986 return 3; 987 case GlobalValue::LinkOnceAnyLinkage: 988 return 18; 989 case GlobalValue::ExternalWeakLinkage: 990 return 7; 991 case GlobalValue::CommonLinkage: 992 return 8; 993 case GlobalValue::PrivateLinkage: 994 return 9; 995 case GlobalValue::WeakODRLinkage: 996 return 17; 997 case GlobalValue::LinkOnceODRLinkage: 998 return 19; 999 case GlobalValue::AvailableExternallyLinkage: 1000 return 12; 1001 } 1002 llvm_unreachable("Invalid linkage"); 1003 } 1004 1005 static unsigned getEncodedLinkage(const GlobalValue &GV) { 1006 return getEncodedLinkage(GV.getLinkage()); 1007 } 1008 1009 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) { 1010 uint64_t RawFlags = 0; 1011 RawFlags |= Flags.ReadNone; 1012 RawFlags |= (Flags.ReadOnly << 1); 1013 RawFlags |= (Flags.NoRecurse << 2); 1014 RawFlags |= (Flags.ReturnDoesNotAlias << 3); 1015 RawFlags |= (Flags.NoInline << 4); 1016 RawFlags |= (Flags.AlwaysInline << 5); 1017 return RawFlags; 1018 } 1019 1020 // Decode the flags for GlobalValue in the summary 1021 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) { 1022 uint64_t RawFlags = 0; 1023 1024 RawFlags |= Flags.NotEligibleToImport; // bool 1025 RawFlags |= (Flags.Live << 1); 1026 RawFlags |= (Flags.DSOLocal << 2); 1027 RawFlags |= (Flags.CanAutoHide << 3); 1028 1029 // Linkage don't need to be remapped at that time for the summary. Any future 1030 // change to the getEncodedLinkage() function will need to be taken into 1031 // account here as well. 1032 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits 1033 1034 return RawFlags; 1035 } 1036 1037 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) { 1038 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) | 1039 (Flags.Constant << 2) | Flags.VCallVisibility << 3; 1040 return RawFlags; 1041 } 1042 1043 static unsigned getEncodedVisibility(const GlobalValue &GV) { 1044 switch (GV.getVisibility()) { 1045 case GlobalValue::DefaultVisibility: return 0; 1046 case GlobalValue::HiddenVisibility: return 1; 1047 case GlobalValue::ProtectedVisibility: return 2; 1048 } 1049 llvm_unreachable("Invalid visibility"); 1050 } 1051 1052 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) { 1053 switch (GV.getDLLStorageClass()) { 1054 case GlobalValue::DefaultStorageClass: return 0; 1055 case GlobalValue::DLLImportStorageClass: return 1; 1056 case GlobalValue::DLLExportStorageClass: return 2; 1057 } 1058 llvm_unreachable("Invalid DLL storage class"); 1059 } 1060 1061 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) { 1062 switch (GV.getThreadLocalMode()) { 1063 case GlobalVariable::NotThreadLocal: return 0; 1064 case GlobalVariable::GeneralDynamicTLSModel: return 1; 1065 case GlobalVariable::LocalDynamicTLSModel: return 2; 1066 case GlobalVariable::InitialExecTLSModel: return 3; 1067 case GlobalVariable::LocalExecTLSModel: return 4; 1068 } 1069 llvm_unreachable("Invalid TLS model"); 1070 } 1071 1072 static unsigned getEncodedComdatSelectionKind(const Comdat &C) { 1073 switch (C.getSelectionKind()) { 1074 case Comdat::Any: 1075 return bitc::COMDAT_SELECTION_KIND_ANY; 1076 case Comdat::ExactMatch: 1077 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH; 1078 case Comdat::Largest: 1079 return bitc::COMDAT_SELECTION_KIND_LARGEST; 1080 case Comdat::NoDuplicates: 1081 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES; 1082 case Comdat::SameSize: 1083 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE; 1084 } 1085 llvm_unreachable("Invalid selection kind"); 1086 } 1087 1088 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) { 1089 switch (GV.getUnnamedAddr()) { 1090 case GlobalValue::UnnamedAddr::None: return 0; 1091 case GlobalValue::UnnamedAddr::Local: return 2; 1092 case GlobalValue::UnnamedAddr::Global: return 1; 1093 } 1094 llvm_unreachable("Invalid unnamed_addr"); 1095 } 1096 1097 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) { 1098 if (GenerateHash) 1099 Hasher.update(Str); 1100 return StrtabBuilder.add(Str); 1101 } 1102 1103 void ModuleBitcodeWriter::writeComdats() { 1104 SmallVector<unsigned, 64> Vals; 1105 for (const Comdat *C : VE.getComdats()) { 1106 // COMDAT: [strtab offset, strtab size, selection_kind] 1107 Vals.push_back(addToStrtab(C->getName())); 1108 Vals.push_back(C->getName().size()); 1109 Vals.push_back(getEncodedComdatSelectionKind(*C)); 1110 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0); 1111 Vals.clear(); 1112 } 1113 } 1114 1115 /// Write a record that will eventually hold the word offset of the 1116 /// module-level VST. For now the offset is 0, which will be backpatched 1117 /// after the real VST is written. Saves the bit offset to backpatch. 1118 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() { 1119 // Write a placeholder value in for the offset of the real VST, 1120 // which is written after the function blocks so that it can include 1121 // the offset of each function. The placeholder offset will be 1122 // updated when the real VST is written. 1123 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1124 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET)); 1125 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to 1126 // hold the real VST offset. Must use fixed instead of VBR as we don't 1127 // know how many VBR chunks to reserve ahead of time. 1128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1129 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1130 1131 // Emit the placeholder 1132 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0}; 1133 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals); 1134 1135 // Compute and save the bit offset to the placeholder, which will be 1136 // patched when the real VST is written. We can simply subtract the 32-bit 1137 // fixed size from the current bit number to get the location to backpatch. 1138 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32; 1139 } 1140 1141 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 }; 1142 1143 /// Determine the encoding to use for the given string name and length. 1144 static StringEncoding getStringEncoding(StringRef Str) { 1145 bool isChar6 = true; 1146 for (char C : Str) { 1147 if (isChar6) 1148 isChar6 = BitCodeAbbrevOp::isChar6(C); 1149 if ((unsigned char)C & 128) 1150 // don't bother scanning the rest. 1151 return SE_Fixed8; 1152 } 1153 if (isChar6) 1154 return SE_Char6; 1155 return SE_Fixed7; 1156 } 1157 1158 /// Emit top-level description of module, including target triple, inline asm, 1159 /// descriptors for global variables, and function prototype info. 1160 /// Returns the bit offset to backpatch with the location of the real VST. 1161 void ModuleBitcodeWriter::writeModuleInfo() { 1162 // Emit various pieces of data attached to a module. 1163 if (!M.getTargetTriple().empty()) 1164 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(), 1165 0 /*TODO*/); 1166 const std::string &DL = M.getDataLayoutStr(); 1167 if (!DL.empty()) 1168 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/); 1169 if (!M.getModuleInlineAsm().empty()) 1170 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(), 1171 0 /*TODO*/); 1172 1173 // Emit information about sections and GC, computing how many there are. Also 1174 // compute the maximum alignment value. 1175 std::map<std::string, unsigned> SectionMap; 1176 std::map<std::string, unsigned> GCMap; 1177 unsigned MaxAlignment = 0; 1178 unsigned MaxGlobalType = 0; 1179 for (const GlobalValue &GV : M.globals()) { 1180 MaxAlignment = std::max(MaxAlignment, GV.getAlignment()); 1181 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType())); 1182 if (GV.hasSection()) { 1183 // Give section names unique ID's. 1184 unsigned &Entry = SectionMap[std::string(GV.getSection())]; 1185 if (!Entry) { 1186 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(), 1187 0 /*TODO*/); 1188 Entry = SectionMap.size(); 1189 } 1190 } 1191 } 1192 for (const Function &F : M) { 1193 MaxAlignment = std::max(MaxAlignment, F.getAlignment()); 1194 if (F.hasSection()) { 1195 // Give section names unique ID's. 1196 unsigned &Entry = SectionMap[std::string(F.getSection())]; 1197 if (!Entry) { 1198 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(), 1199 0 /*TODO*/); 1200 Entry = SectionMap.size(); 1201 } 1202 } 1203 if (F.hasGC()) { 1204 // Same for GC names. 1205 unsigned &Entry = GCMap[F.getGC()]; 1206 if (!Entry) { 1207 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(), 1208 0 /*TODO*/); 1209 Entry = GCMap.size(); 1210 } 1211 } 1212 } 1213 1214 // Emit abbrev for globals, now that we know # sections and max alignment. 1215 unsigned SimpleGVarAbbrev = 0; 1216 if (!M.global_empty()) { 1217 // Add an abbrev for common globals with no visibility or thread localness. 1218 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1219 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 1220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1223 Log2_32_Ceil(MaxGlobalType+1))); 1224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2 1225 //| explicitType << 1 1226 //| constant 1227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 1228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage. 1229 if (MaxAlignment == 0) // Alignment. 1230 Abbv->Add(BitCodeAbbrevOp(0)); 1231 else { 1232 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 1233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1234 Log2_32_Ceil(MaxEncAlignment+1))); 1235 } 1236 if (SectionMap.empty()) // Section. 1237 Abbv->Add(BitCodeAbbrevOp(0)); 1238 else 1239 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1240 Log2_32_Ceil(SectionMap.size()+1))); 1241 // Don't bother emitting vis + thread local. 1242 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1243 } 1244 1245 SmallVector<unsigned, 64> Vals; 1246 // Emit the module's source file name. 1247 { 1248 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 1249 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 1250 if (Bits == SE_Char6) 1251 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 1252 else if (Bits == SE_Fixed7) 1253 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 1254 1255 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 1256 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1257 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 1258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1259 Abbv->Add(AbbrevOpToUse); 1260 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 1261 1262 for (const auto P : M.getSourceFileName()) 1263 Vals.push_back((unsigned char)P); 1264 1265 // Emit the finished record. 1266 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 1267 Vals.clear(); 1268 } 1269 1270 // Emit the global variable information. 1271 for (const GlobalVariable &GV : M.globals()) { 1272 unsigned AbbrevToUse = 0; 1273 1274 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid, 1275 // linkage, alignment, section, visibility, threadlocal, 1276 // unnamed_addr, externally_initialized, dllstorageclass, 1277 // comdat, attributes, DSO_Local] 1278 Vals.push_back(addToStrtab(GV.getName())); 1279 Vals.push_back(GV.getName().size()); 1280 Vals.push_back(VE.getTypeID(GV.getValueType())); 1281 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant()); 1282 Vals.push_back(GV.isDeclaration() ? 0 : 1283 (VE.getValueID(GV.getInitializer()) + 1)); 1284 Vals.push_back(getEncodedLinkage(GV)); 1285 Vals.push_back(Log2_32(GV.getAlignment())+1); 1286 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())] 1287 : 0); 1288 if (GV.isThreadLocal() || 1289 GV.getVisibility() != GlobalValue::DefaultVisibility || 1290 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || 1291 GV.isExternallyInitialized() || 1292 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || 1293 GV.hasComdat() || 1294 GV.hasAttributes() || 1295 GV.isDSOLocal() || 1296 GV.hasPartition()) { 1297 Vals.push_back(getEncodedVisibility(GV)); 1298 Vals.push_back(getEncodedThreadLocalMode(GV)); 1299 Vals.push_back(getEncodedUnnamedAddr(GV)); 1300 Vals.push_back(GV.isExternallyInitialized()); 1301 Vals.push_back(getEncodedDLLStorageClass(GV)); 1302 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); 1303 1304 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex); 1305 Vals.push_back(VE.getAttributeListID(AL)); 1306 1307 Vals.push_back(GV.isDSOLocal()); 1308 Vals.push_back(addToStrtab(GV.getPartition())); 1309 Vals.push_back(GV.getPartition().size()); 1310 } else { 1311 AbbrevToUse = SimpleGVarAbbrev; 1312 } 1313 1314 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 1315 Vals.clear(); 1316 } 1317 1318 // Emit the function proto information. 1319 for (const Function &F : M) { 1320 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto, 1321 // linkage, paramattrs, alignment, section, visibility, gc, 1322 // unnamed_addr, prologuedata, dllstorageclass, comdat, 1323 // prefixdata, personalityfn, DSO_Local, addrspace] 1324 Vals.push_back(addToStrtab(F.getName())); 1325 Vals.push_back(F.getName().size()); 1326 Vals.push_back(VE.getTypeID(F.getFunctionType())); 1327 Vals.push_back(F.getCallingConv()); 1328 Vals.push_back(F.isDeclaration()); 1329 Vals.push_back(getEncodedLinkage(F)); 1330 Vals.push_back(VE.getAttributeListID(F.getAttributes())); 1331 Vals.push_back(Log2_32(F.getAlignment())+1); 1332 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())] 1333 : 0); 1334 Vals.push_back(getEncodedVisibility(F)); 1335 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0); 1336 Vals.push_back(getEncodedUnnamedAddr(F)); 1337 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) 1338 : 0); 1339 Vals.push_back(getEncodedDLLStorageClass(F)); 1340 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0); 1341 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1) 1342 : 0); 1343 Vals.push_back( 1344 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0); 1345 1346 Vals.push_back(F.isDSOLocal()); 1347 Vals.push_back(F.getAddressSpace()); 1348 Vals.push_back(addToStrtab(F.getPartition())); 1349 Vals.push_back(F.getPartition().size()); 1350 1351 unsigned AbbrevToUse = 0; 1352 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 1353 Vals.clear(); 1354 } 1355 1356 // Emit the alias information. 1357 for (const GlobalAlias &A : M.aliases()) { 1358 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage, 1359 // visibility, dllstorageclass, threadlocal, unnamed_addr, 1360 // DSO_Local] 1361 Vals.push_back(addToStrtab(A.getName())); 1362 Vals.push_back(A.getName().size()); 1363 Vals.push_back(VE.getTypeID(A.getValueType())); 1364 Vals.push_back(A.getType()->getAddressSpace()); 1365 Vals.push_back(VE.getValueID(A.getAliasee())); 1366 Vals.push_back(getEncodedLinkage(A)); 1367 Vals.push_back(getEncodedVisibility(A)); 1368 Vals.push_back(getEncodedDLLStorageClass(A)); 1369 Vals.push_back(getEncodedThreadLocalMode(A)); 1370 Vals.push_back(getEncodedUnnamedAddr(A)); 1371 Vals.push_back(A.isDSOLocal()); 1372 Vals.push_back(addToStrtab(A.getPartition())); 1373 Vals.push_back(A.getPartition().size()); 1374 1375 unsigned AbbrevToUse = 0; 1376 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 1377 Vals.clear(); 1378 } 1379 1380 // Emit the ifunc information. 1381 for (const GlobalIFunc &I : M.ifuncs()) { 1382 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver 1383 // val#, linkage, visibility, DSO_Local] 1384 Vals.push_back(addToStrtab(I.getName())); 1385 Vals.push_back(I.getName().size()); 1386 Vals.push_back(VE.getTypeID(I.getValueType())); 1387 Vals.push_back(I.getType()->getAddressSpace()); 1388 Vals.push_back(VE.getValueID(I.getResolver())); 1389 Vals.push_back(getEncodedLinkage(I)); 1390 Vals.push_back(getEncodedVisibility(I)); 1391 Vals.push_back(I.isDSOLocal()); 1392 Vals.push_back(addToStrtab(I.getPartition())); 1393 Vals.push_back(I.getPartition().size()); 1394 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 1395 Vals.clear(); 1396 } 1397 1398 writeValueSymbolTableForwardDecl(); 1399 } 1400 1401 static uint64_t getOptimizationFlags(const Value *V) { 1402 uint64_t Flags = 0; 1403 1404 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) { 1405 if (OBO->hasNoSignedWrap()) 1406 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 1407 if (OBO->hasNoUnsignedWrap()) 1408 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 1409 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) { 1410 if (PEO->isExact()) 1411 Flags |= 1 << bitc::PEO_EXACT; 1412 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) { 1413 if (FPMO->hasAllowReassoc()) 1414 Flags |= bitc::AllowReassoc; 1415 if (FPMO->hasNoNaNs()) 1416 Flags |= bitc::NoNaNs; 1417 if (FPMO->hasNoInfs()) 1418 Flags |= bitc::NoInfs; 1419 if (FPMO->hasNoSignedZeros()) 1420 Flags |= bitc::NoSignedZeros; 1421 if (FPMO->hasAllowReciprocal()) 1422 Flags |= bitc::AllowReciprocal; 1423 if (FPMO->hasAllowContract()) 1424 Flags |= bitc::AllowContract; 1425 if (FPMO->hasApproxFunc()) 1426 Flags |= bitc::ApproxFunc; 1427 } 1428 1429 return Flags; 1430 } 1431 1432 void ModuleBitcodeWriter::writeValueAsMetadata( 1433 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) { 1434 // Mimic an MDNode with a value as one operand. 1435 Value *V = MD->getValue(); 1436 Record.push_back(VE.getTypeID(V->getType())); 1437 Record.push_back(VE.getValueID(V)); 1438 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0); 1439 Record.clear(); 1440 } 1441 1442 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N, 1443 SmallVectorImpl<uint64_t> &Record, 1444 unsigned Abbrev) { 1445 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1446 Metadata *MD = N->getOperand(i); 1447 assert(!(MD && isa<LocalAsMetadata>(MD)) && 1448 "Unexpected function-local metadata"); 1449 Record.push_back(VE.getMetadataOrNullID(MD)); 1450 } 1451 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE 1452 : bitc::METADATA_NODE, 1453 Record, Abbrev); 1454 Record.clear(); 1455 } 1456 1457 unsigned ModuleBitcodeWriter::createDILocationAbbrev() { 1458 // Assume the column is usually under 128, and always output the inlined-at 1459 // location (it's never more expensive than building an array size 1). 1460 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1461 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION)); 1462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1468 return Stream.EmitAbbrev(std::move(Abbv)); 1469 } 1470 1471 void ModuleBitcodeWriter::writeDILocation(const DILocation *N, 1472 SmallVectorImpl<uint64_t> &Record, 1473 unsigned &Abbrev) { 1474 if (!Abbrev) 1475 Abbrev = createDILocationAbbrev(); 1476 1477 Record.push_back(N->isDistinct()); 1478 Record.push_back(N->getLine()); 1479 Record.push_back(N->getColumn()); 1480 Record.push_back(VE.getMetadataID(N->getScope())); 1481 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt())); 1482 Record.push_back(N->isImplicitCode()); 1483 1484 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev); 1485 Record.clear(); 1486 } 1487 1488 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() { 1489 // Assume the column is usually under 128, and always output the inlined-at 1490 // location (it's never more expensive than building an array size 1). 1491 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1492 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG)); 1493 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1494 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 1496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 1499 return Stream.EmitAbbrev(std::move(Abbv)); 1500 } 1501 1502 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N, 1503 SmallVectorImpl<uint64_t> &Record, 1504 unsigned &Abbrev) { 1505 if (!Abbrev) 1506 Abbrev = createGenericDINodeAbbrev(); 1507 1508 Record.push_back(N->isDistinct()); 1509 Record.push_back(N->getTag()); 1510 Record.push_back(0); // Per-tag version field; unused for now. 1511 1512 for (auto &I : N->operands()) 1513 Record.push_back(VE.getMetadataOrNullID(I)); 1514 1515 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev); 1516 Record.clear(); 1517 } 1518 1519 static uint64_t rotateSign(int64_t I) { 1520 uint64_t U = I; 1521 return I < 0 ? ~(U << 1) : U << 1; 1522 } 1523 1524 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N, 1525 SmallVectorImpl<uint64_t> &Record, 1526 unsigned Abbrev) { 1527 const uint64_t Version = 1 << 1; 1528 Record.push_back((uint64_t)N->isDistinct() | Version); 1529 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode())); 1530 Record.push_back(rotateSign(N->getLowerBound())); 1531 1532 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev); 1533 Record.clear(); 1534 } 1535 1536 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 1537 if ((int64_t)V >= 0) 1538 Vals.push_back(V << 1); 1539 else 1540 Vals.push_back((-V << 1) | 1); 1541 } 1542 1543 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) { 1544 // We have an arbitrary precision integer value to write whose 1545 // bit width is > 64. However, in canonical unsigned integer 1546 // format it is likely that the high bits are going to be zero. 1547 // So, we only write the number of active words. 1548 unsigned NumWords = A.getActiveWords(); 1549 const uint64_t *RawData = A.getRawData(); 1550 for (unsigned i = 0; i < NumWords; i++) 1551 emitSignedInt64(Vals, RawData[i]); 1552 } 1553 1554 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N, 1555 SmallVectorImpl<uint64_t> &Record, 1556 unsigned Abbrev) { 1557 const uint64_t IsBigInt = 1 << 2; 1558 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct()); 1559 Record.push_back(N->getValue().getBitWidth()); 1560 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1561 emitWideAPInt(Record, N->getValue()); 1562 1563 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev); 1564 Record.clear(); 1565 } 1566 1567 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N, 1568 SmallVectorImpl<uint64_t> &Record, 1569 unsigned Abbrev) { 1570 Record.push_back(N->isDistinct()); 1571 Record.push_back(N->getTag()); 1572 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1573 Record.push_back(N->getSizeInBits()); 1574 Record.push_back(N->getAlignInBits()); 1575 Record.push_back(N->getEncoding()); 1576 Record.push_back(N->getFlags()); 1577 1578 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev); 1579 Record.clear(); 1580 } 1581 1582 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N, 1583 SmallVectorImpl<uint64_t> &Record, 1584 unsigned Abbrev) { 1585 Record.push_back(N->isDistinct()); 1586 Record.push_back(N->getTag()); 1587 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1588 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1589 Record.push_back(N->getLine()); 1590 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1591 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1592 Record.push_back(N->getSizeInBits()); 1593 Record.push_back(N->getAlignInBits()); 1594 Record.push_back(N->getOffsetInBits()); 1595 Record.push_back(N->getFlags()); 1596 Record.push_back(VE.getMetadataOrNullID(N->getExtraData())); 1597 1598 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means 1599 // that there is no DWARF address space associated with DIDerivedType. 1600 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 1601 Record.push_back(*DWARFAddressSpace + 1); 1602 else 1603 Record.push_back(0); 1604 1605 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev); 1606 Record.clear(); 1607 } 1608 1609 void ModuleBitcodeWriter::writeDICompositeType( 1610 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record, 1611 unsigned Abbrev) { 1612 const unsigned IsNotUsedInOldTypeRef = 0x2; 1613 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct()); 1614 Record.push_back(N->getTag()); 1615 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1616 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1617 Record.push_back(N->getLine()); 1618 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1619 Record.push_back(VE.getMetadataOrNullID(N->getBaseType())); 1620 Record.push_back(N->getSizeInBits()); 1621 Record.push_back(N->getAlignInBits()); 1622 Record.push_back(N->getOffsetInBits()); 1623 Record.push_back(N->getFlags()); 1624 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1625 Record.push_back(N->getRuntimeLang()); 1626 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder())); 1627 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1628 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier())); 1629 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator())); 1630 1631 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev); 1632 Record.clear(); 1633 } 1634 1635 void ModuleBitcodeWriter::writeDISubroutineType( 1636 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record, 1637 unsigned Abbrev) { 1638 const unsigned HasNoOldTypeRefs = 0x2; 1639 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct()); 1640 Record.push_back(N->getFlags()); 1641 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get())); 1642 Record.push_back(N->getCC()); 1643 1644 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev); 1645 Record.clear(); 1646 } 1647 1648 void ModuleBitcodeWriter::writeDIFile(const DIFile *N, 1649 SmallVectorImpl<uint64_t> &Record, 1650 unsigned Abbrev) { 1651 Record.push_back(N->isDistinct()); 1652 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename())); 1653 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory())); 1654 if (N->getRawChecksum()) { 1655 Record.push_back(N->getRawChecksum()->Kind); 1656 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value)); 1657 } else { 1658 // Maintain backwards compatibility with the old internal representation of 1659 // CSK_None in ChecksumKind by writing nulls here when Checksum is None. 1660 Record.push_back(0); 1661 Record.push_back(VE.getMetadataOrNullID(nullptr)); 1662 } 1663 auto Source = N->getRawSource(); 1664 if (Source) 1665 Record.push_back(VE.getMetadataOrNullID(*Source)); 1666 1667 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev); 1668 Record.clear(); 1669 } 1670 1671 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N, 1672 SmallVectorImpl<uint64_t> &Record, 1673 unsigned Abbrev) { 1674 assert(N->isDistinct() && "Expected distinct compile units"); 1675 Record.push_back(/* IsDistinct */ true); 1676 Record.push_back(N->getSourceLanguage()); 1677 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1678 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer())); 1679 Record.push_back(N->isOptimized()); 1680 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags())); 1681 Record.push_back(N->getRuntimeVersion()); 1682 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename())); 1683 Record.push_back(N->getEmissionKind()); 1684 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get())); 1685 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get())); 1686 Record.push_back(/* subprograms */ 0); 1687 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get())); 1688 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get())); 1689 Record.push_back(N->getDWOId()); 1690 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get())); 1691 Record.push_back(N->getSplitDebugInlining()); 1692 Record.push_back(N->getDebugInfoForProfiling()); 1693 Record.push_back((unsigned)N->getNameTableKind()); 1694 Record.push_back(N->getRangesBaseAddress()); 1695 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot())); 1696 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK())); 1697 1698 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev); 1699 Record.clear(); 1700 } 1701 1702 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N, 1703 SmallVectorImpl<uint64_t> &Record, 1704 unsigned Abbrev) { 1705 const uint64_t HasUnitFlag = 1 << 1; 1706 const uint64_t HasSPFlagsFlag = 1 << 2; 1707 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag); 1708 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1709 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1710 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1711 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1712 Record.push_back(N->getLine()); 1713 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1714 Record.push_back(N->getScopeLine()); 1715 Record.push_back(VE.getMetadataOrNullID(N->getContainingType())); 1716 Record.push_back(N->getSPFlags()); 1717 Record.push_back(N->getVirtualIndex()); 1718 Record.push_back(N->getFlags()); 1719 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit())); 1720 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get())); 1721 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration())); 1722 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get())); 1723 Record.push_back(N->getThisAdjustment()); 1724 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get())); 1725 1726 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev); 1727 Record.clear(); 1728 } 1729 1730 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N, 1731 SmallVectorImpl<uint64_t> &Record, 1732 unsigned Abbrev) { 1733 Record.push_back(N->isDistinct()); 1734 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1735 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1736 Record.push_back(N->getLine()); 1737 Record.push_back(N->getColumn()); 1738 1739 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev); 1740 Record.clear(); 1741 } 1742 1743 void ModuleBitcodeWriter::writeDILexicalBlockFile( 1744 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record, 1745 unsigned Abbrev) { 1746 Record.push_back(N->isDistinct()); 1747 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1748 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1749 Record.push_back(N->getDiscriminator()); 1750 1751 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev); 1752 Record.clear(); 1753 } 1754 1755 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N, 1756 SmallVectorImpl<uint64_t> &Record, 1757 unsigned Abbrev) { 1758 Record.push_back(N->isDistinct()); 1759 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1760 Record.push_back(VE.getMetadataOrNullID(N->getDecl())); 1761 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1762 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1763 Record.push_back(N->getLineNo()); 1764 1765 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev); 1766 Record.clear(); 1767 } 1768 1769 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N, 1770 SmallVectorImpl<uint64_t> &Record, 1771 unsigned Abbrev) { 1772 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1); 1773 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1774 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1775 1776 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev); 1777 Record.clear(); 1778 } 1779 1780 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N, 1781 SmallVectorImpl<uint64_t> &Record, 1782 unsigned Abbrev) { 1783 Record.push_back(N->isDistinct()); 1784 Record.push_back(N->getMacinfoType()); 1785 Record.push_back(N->getLine()); 1786 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1787 Record.push_back(VE.getMetadataOrNullID(N->getRawValue())); 1788 1789 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev); 1790 Record.clear(); 1791 } 1792 1793 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N, 1794 SmallVectorImpl<uint64_t> &Record, 1795 unsigned Abbrev) { 1796 Record.push_back(N->isDistinct()); 1797 Record.push_back(N->getMacinfoType()); 1798 Record.push_back(N->getLine()); 1799 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1800 Record.push_back(VE.getMetadataOrNullID(N->getElements().get())); 1801 1802 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev); 1803 Record.clear(); 1804 } 1805 1806 void ModuleBitcodeWriter::writeDIModule(const DIModule *N, 1807 SmallVectorImpl<uint64_t> &Record, 1808 unsigned Abbrev) { 1809 Record.push_back(N->isDistinct()); 1810 for (auto &I : N->operands()) 1811 Record.push_back(VE.getMetadataOrNullID(I)); 1812 1813 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev); 1814 Record.clear(); 1815 } 1816 1817 void ModuleBitcodeWriter::writeDITemplateTypeParameter( 1818 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record, 1819 unsigned Abbrev) { 1820 Record.push_back(N->isDistinct()); 1821 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1822 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1823 Record.push_back(N->isDefault()); 1824 1825 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev); 1826 Record.clear(); 1827 } 1828 1829 void ModuleBitcodeWriter::writeDITemplateValueParameter( 1830 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record, 1831 unsigned Abbrev) { 1832 Record.push_back(N->isDistinct()); 1833 Record.push_back(N->getTag()); 1834 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1835 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1836 Record.push_back(N->isDefault()); 1837 Record.push_back(VE.getMetadataOrNullID(N->getValue())); 1838 1839 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev); 1840 Record.clear(); 1841 } 1842 1843 void ModuleBitcodeWriter::writeDIGlobalVariable( 1844 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record, 1845 unsigned Abbrev) { 1846 const uint64_t Version = 2 << 1; 1847 Record.push_back((uint64_t)N->isDistinct() | Version); 1848 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1849 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1850 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName())); 1851 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1852 Record.push_back(N->getLine()); 1853 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1854 Record.push_back(N->isLocalToUnit()); 1855 Record.push_back(N->isDefinition()); 1856 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration())); 1857 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams())); 1858 Record.push_back(N->getAlignInBits()); 1859 1860 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev); 1861 Record.clear(); 1862 } 1863 1864 void ModuleBitcodeWriter::writeDILocalVariable( 1865 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record, 1866 unsigned Abbrev) { 1867 // In order to support all possible bitcode formats in BitcodeReader we need 1868 // to distinguish the following cases: 1869 // 1) Record has no artificial tag (Record[1]), 1870 // has no obsolete inlinedAt field (Record[9]). 1871 // In this case Record size will be 8, HasAlignment flag is false. 1872 // 2) Record has artificial tag (Record[1]), 1873 // has no obsolete inlignedAt field (Record[9]). 1874 // In this case Record size will be 9, HasAlignment flag is false. 1875 // 3) Record has both artificial tag (Record[1]) and 1876 // obsolete inlignedAt field (Record[9]). 1877 // In this case Record size will be 10, HasAlignment flag is false. 1878 // 4) Record has neither artificial tag, nor inlignedAt field, but 1879 // HasAlignment flag is true and Record[8] contains alignment value. 1880 const uint64_t HasAlignmentFlag = 1 << 1; 1881 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag); 1882 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1883 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1884 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1885 Record.push_back(N->getLine()); 1886 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1887 Record.push_back(N->getArg()); 1888 Record.push_back(N->getFlags()); 1889 Record.push_back(N->getAlignInBits()); 1890 1891 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev); 1892 Record.clear(); 1893 } 1894 1895 void ModuleBitcodeWriter::writeDILabel( 1896 const DILabel *N, SmallVectorImpl<uint64_t> &Record, 1897 unsigned Abbrev) { 1898 Record.push_back((uint64_t)N->isDistinct()); 1899 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1900 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1901 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1902 Record.push_back(N->getLine()); 1903 1904 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev); 1905 Record.clear(); 1906 } 1907 1908 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N, 1909 SmallVectorImpl<uint64_t> &Record, 1910 unsigned Abbrev) { 1911 Record.reserve(N->getElements().size() + 1); 1912 const uint64_t Version = 3 << 1; 1913 Record.push_back((uint64_t)N->isDistinct() | Version); 1914 Record.append(N->elements_begin(), N->elements_end()); 1915 1916 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev); 1917 Record.clear(); 1918 } 1919 1920 void ModuleBitcodeWriter::writeDIGlobalVariableExpression( 1921 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record, 1922 unsigned Abbrev) { 1923 Record.push_back(N->isDistinct()); 1924 Record.push_back(VE.getMetadataOrNullID(N->getVariable())); 1925 Record.push_back(VE.getMetadataOrNullID(N->getExpression())); 1926 1927 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev); 1928 Record.clear(); 1929 } 1930 1931 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N, 1932 SmallVectorImpl<uint64_t> &Record, 1933 unsigned Abbrev) { 1934 Record.push_back(N->isDistinct()); 1935 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1936 Record.push_back(VE.getMetadataOrNullID(N->getFile())); 1937 Record.push_back(N->getLine()); 1938 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName())); 1939 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName())); 1940 Record.push_back(N->getAttributes()); 1941 Record.push_back(VE.getMetadataOrNullID(N->getType())); 1942 1943 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev); 1944 Record.clear(); 1945 } 1946 1947 void ModuleBitcodeWriter::writeDIImportedEntity( 1948 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record, 1949 unsigned Abbrev) { 1950 Record.push_back(N->isDistinct()); 1951 Record.push_back(N->getTag()); 1952 Record.push_back(VE.getMetadataOrNullID(N->getScope())); 1953 Record.push_back(VE.getMetadataOrNullID(N->getEntity())); 1954 Record.push_back(N->getLine()); 1955 Record.push_back(VE.getMetadataOrNullID(N->getRawName())); 1956 Record.push_back(VE.getMetadataOrNullID(N->getRawFile())); 1957 1958 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev); 1959 Record.clear(); 1960 } 1961 1962 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() { 1963 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1964 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME)); 1965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1966 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1967 return Stream.EmitAbbrev(std::move(Abbv)); 1968 } 1969 1970 void ModuleBitcodeWriter::writeNamedMetadata( 1971 SmallVectorImpl<uint64_t> &Record) { 1972 if (M.named_metadata_empty()) 1973 return; 1974 1975 unsigned Abbrev = createNamedMetadataAbbrev(); 1976 for (const NamedMDNode &NMD : M.named_metadata()) { 1977 // Write name. 1978 StringRef Str = NMD.getName(); 1979 Record.append(Str.bytes_begin(), Str.bytes_end()); 1980 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev); 1981 Record.clear(); 1982 1983 // Write named metadata operands. 1984 for (const MDNode *N : NMD.operands()) 1985 Record.push_back(VE.getMetadataID(N)); 1986 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 1987 Record.clear(); 1988 } 1989 } 1990 1991 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() { 1992 auto Abbv = std::make_shared<BitCodeAbbrev>(); 1993 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS)); 1994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings 1995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars 1996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1997 return Stream.EmitAbbrev(std::move(Abbv)); 1998 } 1999 2000 /// Write out a record for MDString. 2001 /// 2002 /// All the metadata strings in a metadata block are emitted in a single 2003 /// record. The sizes and strings themselves are shoved into a blob. 2004 void ModuleBitcodeWriter::writeMetadataStrings( 2005 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) { 2006 if (Strings.empty()) 2007 return; 2008 2009 // Start the record with the number of strings. 2010 Record.push_back(bitc::METADATA_STRINGS); 2011 Record.push_back(Strings.size()); 2012 2013 // Emit the sizes of the strings in the blob. 2014 SmallString<256> Blob; 2015 { 2016 BitstreamWriter W(Blob); 2017 for (const Metadata *MD : Strings) 2018 W.EmitVBR(cast<MDString>(MD)->getLength(), 6); 2019 W.FlushToWord(); 2020 } 2021 2022 // Add the offset to the strings to the record. 2023 Record.push_back(Blob.size()); 2024 2025 // Add the strings to the blob. 2026 for (const Metadata *MD : Strings) 2027 Blob.append(cast<MDString>(MD)->getString()); 2028 2029 // Emit the final record. 2030 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob); 2031 Record.clear(); 2032 } 2033 2034 // Generates an enum to use as an index in the Abbrev array of Metadata record. 2035 enum MetadataAbbrev : unsigned { 2036 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID, 2037 #include "llvm/IR/Metadata.def" 2038 LastPlusOne 2039 }; 2040 2041 void ModuleBitcodeWriter::writeMetadataRecords( 2042 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record, 2043 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) { 2044 if (MDs.empty()) 2045 return; 2046 2047 // Initialize MDNode abbreviations. 2048 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0; 2049 #include "llvm/IR/Metadata.def" 2050 2051 for (const Metadata *MD : MDs) { 2052 if (IndexPos) 2053 IndexPos->push_back(Stream.GetCurrentBitNo()); 2054 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2055 assert(N->isResolved() && "Expected forward references to be resolved"); 2056 2057 switch (N->getMetadataID()) { 2058 default: 2059 llvm_unreachable("Invalid MDNode subclass"); 2060 #define HANDLE_MDNODE_LEAF(CLASS) \ 2061 case Metadata::CLASS##Kind: \ 2062 if (MDAbbrevs) \ 2063 write##CLASS(cast<CLASS>(N), Record, \ 2064 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \ 2065 else \ 2066 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \ 2067 continue; 2068 #include "llvm/IR/Metadata.def" 2069 } 2070 } 2071 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record); 2072 } 2073 } 2074 2075 void ModuleBitcodeWriter::writeModuleMetadata() { 2076 if (!VE.hasMDs() && M.named_metadata_empty()) 2077 return; 2078 2079 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4); 2080 SmallVector<uint64_t, 64> Record; 2081 2082 // Emit all abbrevs upfront, so that the reader can jump in the middle of the 2083 // block and load any metadata. 2084 std::vector<unsigned> MDAbbrevs; 2085 2086 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne); 2087 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev(); 2088 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] = 2089 createGenericDINodeAbbrev(); 2090 2091 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2092 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET)); 2093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2094 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2095 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2096 2097 Abbv = std::make_shared<BitCodeAbbrev>(); 2098 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX)); 2099 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 2101 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2102 2103 // Emit MDStrings together upfront. 2104 writeMetadataStrings(VE.getMDStrings(), Record); 2105 2106 // We only emit an index for the metadata record if we have more than a given 2107 // (naive) threshold of metadatas, otherwise it is not worth it. 2108 if (VE.getNonMDStrings().size() > IndexThreshold) { 2109 // Write a placeholder value in for the offset of the metadata index, 2110 // which is written after the records, so that it can include 2111 // the offset of each entry. The placeholder offset will be 2112 // updated after all records are emitted. 2113 uint64_t Vals[] = {0, 0}; 2114 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev); 2115 } 2116 2117 // Compute and save the bit offset to the current position, which will be 2118 // patched when we emit the index later. We can simply subtract the 64-bit 2119 // fixed size from the current bit number to get the location to backpatch. 2120 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo(); 2121 2122 // This index will contain the bitpos for each individual record. 2123 std::vector<uint64_t> IndexPos; 2124 IndexPos.reserve(VE.getNonMDStrings().size()); 2125 2126 // Write all the records 2127 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos); 2128 2129 if (VE.getNonMDStrings().size() > IndexThreshold) { 2130 // Now that we have emitted all the records we will emit the index. But 2131 // first 2132 // backpatch the forward reference so that the reader can skip the records 2133 // efficiently. 2134 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64, 2135 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos); 2136 2137 // Delta encode the index. 2138 uint64_t PreviousValue = IndexOffsetRecordBitPos; 2139 for (auto &Elt : IndexPos) { 2140 auto EltDelta = Elt - PreviousValue; 2141 PreviousValue = Elt; 2142 Elt = EltDelta; 2143 } 2144 // Emit the index record. 2145 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev); 2146 IndexPos.clear(); 2147 } 2148 2149 // Write the named metadata now. 2150 writeNamedMetadata(Record); 2151 2152 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) { 2153 SmallVector<uint64_t, 4> Record; 2154 Record.push_back(VE.getValueID(&GO)); 2155 pushGlobalMetadataAttachment(Record, GO); 2156 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record); 2157 }; 2158 for (const Function &F : M) 2159 if (F.isDeclaration() && F.hasMetadata()) 2160 AddDeclAttachedMetadata(F); 2161 // FIXME: Only store metadata for declarations here, and move data for global 2162 // variable definitions to a separate block (PR28134). 2163 for (const GlobalVariable &GV : M.globals()) 2164 if (GV.hasMetadata()) 2165 AddDeclAttachedMetadata(GV); 2166 2167 Stream.ExitBlock(); 2168 } 2169 2170 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) { 2171 if (!VE.hasMDs()) 2172 return; 2173 2174 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 2175 SmallVector<uint64_t, 64> Record; 2176 writeMetadataStrings(VE.getMDStrings(), Record); 2177 writeMetadataRecords(VE.getNonMDStrings(), Record); 2178 Stream.ExitBlock(); 2179 } 2180 2181 void ModuleBitcodeWriter::pushGlobalMetadataAttachment( 2182 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) { 2183 // [n x [id, mdnode]] 2184 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2185 GO.getAllMetadata(MDs); 2186 for (const auto &I : MDs) { 2187 Record.push_back(I.first); 2188 Record.push_back(VE.getMetadataID(I.second)); 2189 } 2190 } 2191 2192 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) { 2193 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 2194 2195 SmallVector<uint64_t, 64> Record; 2196 2197 if (F.hasMetadata()) { 2198 pushGlobalMetadataAttachment(Record, F); 2199 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2200 Record.clear(); 2201 } 2202 2203 // Write metadata attachments 2204 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 2205 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2206 for (const BasicBlock &BB : F) 2207 for (const Instruction &I : BB) { 2208 MDs.clear(); 2209 I.getAllMetadataOtherThanDebugLoc(MDs); 2210 2211 // If no metadata, ignore instruction. 2212 if (MDs.empty()) continue; 2213 2214 Record.push_back(VE.getInstructionID(&I)); 2215 2216 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 2217 Record.push_back(MDs[i].first); 2218 Record.push_back(VE.getMetadataID(MDs[i].second)); 2219 } 2220 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 2221 Record.clear(); 2222 } 2223 2224 Stream.ExitBlock(); 2225 } 2226 2227 void ModuleBitcodeWriter::writeModuleMetadataKinds() { 2228 SmallVector<uint64_t, 64> Record; 2229 2230 // Write metadata kinds 2231 // METADATA_KIND - [n x [id, name]] 2232 SmallVector<StringRef, 8> Names; 2233 M.getMDKindNames(Names); 2234 2235 if (Names.empty()) return; 2236 2237 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3); 2238 2239 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 2240 Record.push_back(MDKindID); 2241 StringRef KName = Names[MDKindID]; 2242 Record.append(KName.begin(), KName.end()); 2243 2244 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 2245 Record.clear(); 2246 } 2247 2248 Stream.ExitBlock(); 2249 } 2250 2251 void ModuleBitcodeWriter::writeOperandBundleTags() { 2252 // Write metadata kinds 2253 // 2254 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG 2255 // 2256 // OPERAND_BUNDLE_TAG - [strchr x N] 2257 2258 SmallVector<StringRef, 8> Tags; 2259 M.getOperandBundleTags(Tags); 2260 2261 if (Tags.empty()) 2262 return; 2263 2264 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3); 2265 2266 SmallVector<uint64_t, 64> Record; 2267 2268 for (auto Tag : Tags) { 2269 Record.append(Tag.begin(), Tag.end()); 2270 2271 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0); 2272 Record.clear(); 2273 } 2274 2275 Stream.ExitBlock(); 2276 } 2277 2278 void ModuleBitcodeWriter::writeSyncScopeNames() { 2279 SmallVector<StringRef, 8> SSNs; 2280 M.getContext().getSyncScopeNames(SSNs); 2281 if (SSNs.empty()) 2282 return; 2283 2284 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2); 2285 2286 SmallVector<uint64_t, 64> Record; 2287 for (auto SSN : SSNs) { 2288 Record.append(SSN.begin(), SSN.end()); 2289 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0); 2290 Record.clear(); 2291 } 2292 2293 Stream.ExitBlock(); 2294 } 2295 2296 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, 2297 bool isGlobal) { 2298 if (FirstVal == LastVal) return; 2299 2300 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 2301 2302 unsigned AggregateAbbrev = 0; 2303 unsigned String8Abbrev = 0; 2304 unsigned CString7Abbrev = 0; 2305 unsigned CString6Abbrev = 0; 2306 // If this is a constant pool for the module, emit module-specific abbrevs. 2307 if (isGlobal) { 2308 // Abbrev for CST_CODE_AGGREGATE. 2309 auto Abbv = std::make_shared<BitCodeAbbrev>(); 2310 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 2311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 2313 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 2314 2315 // Abbrev for CST_CODE_STRING. 2316 Abbv = std::make_shared<BitCodeAbbrev>(); 2317 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 2318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 2320 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2321 // Abbrev for CST_CODE_CSTRING. 2322 Abbv = std::make_shared<BitCodeAbbrev>(); 2323 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 2326 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2327 // Abbrev for CST_CODE_CSTRING. 2328 Abbv = std::make_shared<BitCodeAbbrev>(); 2329 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 2330 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 2331 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 2332 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv)); 2333 } 2334 2335 SmallVector<uint64_t, 64> Record; 2336 2337 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2338 Type *LastTy = nullptr; 2339 for (unsigned i = FirstVal; i != LastVal; ++i) { 2340 const Value *V = Vals[i].first; 2341 // If we need to switch types, do so now. 2342 if (V->getType() != LastTy) { 2343 LastTy = V->getType(); 2344 Record.push_back(VE.getTypeID(LastTy)); 2345 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 2346 CONSTANTS_SETTYPE_ABBREV); 2347 Record.clear(); 2348 } 2349 2350 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2351 Record.push_back(unsigned(IA->hasSideEffects()) | 2352 unsigned(IA->isAlignStack()) << 1 | 2353 unsigned(IA->getDialect()&1) << 2); 2354 2355 // Add the asm string. 2356 const std::string &AsmStr = IA->getAsmString(); 2357 Record.push_back(AsmStr.size()); 2358 Record.append(AsmStr.begin(), AsmStr.end()); 2359 2360 // Add the constraint string. 2361 const std::string &ConstraintStr = IA->getConstraintString(); 2362 Record.push_back(ConstraintStr.size()); 2363 Record.append(ConstraintStr.begin(), ConstraintStr.end()); 2364 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 2365 Record.clear(); 2366 continue; 2367 } 2368 const Constant *C = cast<Constant>(V); 2369 unsigned Code = -1U; 2370 unsigned AbbrevToUse = 0; 2371 if (C->isNullValue()) { 2372 Code = bitc::CST_CODE_NULL; 2373 } else if (isa<UndefValue>(C)) { 2374 Code = bitc::CST_CODE_UNDEF; 2375 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 2376 if (IV->getBitWidth() <= 64) { 2377 uint64_t V = IV->getSExtValue(); 2378 emitSignedInt64(Record, V); 2379 Code = bitc::CST_CODE_INTEGER; 2380 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 2381 } else { // Wide integers, > 64 bits in size. 2382 emitWideAPInt(Record, IV->getValue()); 2383 Code = bitc::CST_CODE_WIDE_INTEGER; 2384 } 2385 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 2386 Code = bitc::CST_CODE_FLOAT; 2387 Type *Ty = CFP->getType(); 2388 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 2389 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 2390 } else if (Ty->isX86_FP80Ty()) { 2391 // api needed to prevent premature destruction 2392 // bits are not in the same order as a normal i80 APInt, compensate. 2393 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2394 const uint64_t *p = api.getRawData(); 2395 Record.push_back((p[1] << 48) | (p[0] >> 16)); 2396 Record.push_back(p[0] & 0xffffLL); 2397 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 2398 APInt api = CFP->getValueAPF().bitcastToAPInt(); 2399 const uint64_t *p = api.getRawData(); 2400 Record.push_back(p[0]); 2401 Record.push_back(p[1]); 2402 } else { 2403 assert(0 && "Unknown FP type!"); 2404 } 2405 } else if (isa<ConstantDataSequential>(C) && 2406 cast<ConstantDataSequential>(C)->isString()) { 2407 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 2408 // Emit constant strings specially. 2409 unsigned NumElts = Str->getNumElements(); 2410 // If this is a null-terminated string, use the denser CSTRING encoding. 2411 if (Str->isCString()) { 2412 Code = bitc::CST_CODE_CSTRING; 2413 --NumElts; // Don't encode the null, which isn't allowed by char6. 2414 } else { 2415 Code = bitc::CST_CODE_STRING; 2416 AbbrevToUse = String8Abbrev; 2417 } 2418 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 2419 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 2420 for (unsigned i = 0; i != NumElts; ++i) { 2421 unsigned char V = Str->getElementAsInteger(i); 2422 Record.push_back(V); 2423 isCStr7 &= (V & 128) == 0; 2424 if (isCStrChar6) 2425 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 2426 } 2427 2428 if (isCStrChar6) 2429 AbbrevToUse = CString6Abbrev; 2430 else if (isCStr7) 2431 AbbrevToUse = CString7Abbrev; 2432 } else if (const ConstantDataSequential *CDS = 2433 dyn_cast<ConstantDataSequential>(C)) { 2434 Code = bitc::CST_CODE_DATA; 2435 Type *EltTy = CDS->getElementType(); 2436 if (isa<IntegerType>(EltTy)) { 2437 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2438 Record.push_back(CDS->getElementAsInteger(i)); 2439 } else { 2440 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 2441 Record.push_back( 2442 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue()); 2443 } 2444 } else if (isa<ConstantAggregate>(C)) { 2445 Code = bitc::CST_CODE_AGGREGATE; 2446 for (const Value *Op : C->operands()) 2447 Record.push_back(VE.getValueID(Op)); 2448 AbbrevToUse = AggregateAbbrev; 2449 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2450 switch (CE->getOpcode()) { 2451 default: 2452 if (Instruction::isCast(CE->getOpcode())) { 2453 Code = bitc::CST_CODE_CE_CAST; 2454 Record.push_back(getEncodedCastOpcode(CE->getOpcode())); 2455 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2456 Record.push_back(VE.getValueID(C->getOperand(0))); 2457 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 2458 } else { 2459 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 2460 Code = bitc::CST_CODE_CE_BINOP; 2461 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode())); 2462 Record.push_back(VE.getValueID(C->getOperand(0))); 2463 Record.push_back(VE.getValueID(C->getOperand(1))); 2464 uint64_t Flags = getOptimizationFlags(CE); 2465 if (Flags != 0) 2466 Record.push_back(Flags); 2467 } 2468 break; 2469 case Instruction::FNeg: { 2470 assert(CE->getNumOperands() == 1 && "Unknown constant expr!"); 2471 Code = bitc::CST_CODE_CE_UNOP; 2472 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode())); 2473 Record.push_back(VE.getValueID(C->getOperand(0))); 2474 uint64_t Flags = getOptimizationFlags(CE); 2475 if (Flags != 0) 2476 Record.push_back(Flags); 2477 break; 2478 } 2479 case Instruction::GetElementPtr: { 2480 Code = bitc::CST_CODE_CE_GEP; 2481 const auto *GO = cast<GEPOperator>(C); 2482 Record.push_back(VE.getTypeID(GO->getSourceElementType())); 2483 if (Optional<unsigned> Idx = GO->getInRangeIndex()) { 2484 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX; 2485 Record.push_back((*Idx << 1) | GO->isInBounds()); 2486 } else if (GO->isInBounds()) 2487 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 2488 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 2489 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 2490 Record.push_back(VE.getValueID(C->getOperand(i))); 2491 } 2492 break; 2493 } 2494 case Instruction::Select: 2495 Code = bitc::CST_CODE_CE_SELECT; 2496 Record.push_back(VE.getValueID(C->getOperand(0))); 2497 Record.push_back(VE.getValueID(C->getOperand(1))); 2498 Record.push_back(VE.getValueID(C->getOperand(2))); 2499 break; 2500 case Instruction::ExtractElement: 2501 Code = bitc::CST_CODE_CE_EXTRACTELT; 2502 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2503 Record.push_back(VE.getValueID(C->getOperand(0))); 2504 Record.push_back(VE.getTypeID(C->getOperand(1)->getType())); 2505 Record.push_back(VE.getValueID(C->getOperand(1))); 2506 break; 2507 case Instruction::InsertElement: 2508 Code = bitc::CST_CODE_CE_INSERTELT; 2509 Record.push_back(VE.getValueID(C->getOperand(0))); 2510 Record.push_back(VE.getValueID(C->getOperand(1))); 2511 Record.push_back(VE.getTypeID(C->getOperand(2)->getType())); 2512 Record.push_back(VE.getValueID(C->getOperand(2))); 2513 break; 2514 case Instruction::ShuffleVector: 2515 // If the return type and argument types are the same, this is a 2516 // standard shufflevector instruction. If the types are different, 2517 // then the shuffle is widening or truncating the input vectors, and 2518 // the argument type must also be encoded. 2519 if (C->getType() == C->getOperand(0)->getType()) { 2520 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 2521 } else { 2522 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 2523 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2524 } 2525 Record.push_back(VE.getValueID(C->getOperand(0))); 2526 Record.push_back(VE.getValueID(C->getOperand(1))); 2527 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode())); 2528 break; 2529 case Instruction::ICmp: 2530 case Instruction::FCmp: 2531 Code = bitc::CST_CODE_CE_CMP; 2532 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 2533 Record.push_back(VE.getValueID(C->getOperand(0))); 2534 Record.push_back(VE.getValueID(C->getOperand(1))); 2535 Record.push_back(CE->getPredicate()); 2536 break; 2537 } 2538 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 2539 Code = bitc::CST_CODE_BLOCKADDRESS; 2540 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 2541 Record.push_back(VE.getValueID(BA->getFunction())); 2542 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 2543 } else { 2544 #ifndef NDEBUG 2545 C->dump(); 2546 #endif 2547 llvm_unreachable("Unknown constant!"); 2548 } 2549 Stream.EmitRecord(Code, Record, AbbrevToUse); 2550 Record.clear(); 2551 } 2552 2553 Stream.ExitBlock(); 2554 } 2555 2556 void ModuleBitcodeWriter::writeModuleConstants() { 2557 const ValueEnumerator::ValueList &Vals = VE.getValues(); 2558 2559 // Find the first constant to emit, which is the first non-globalvalue value. 2560 // We know globalvalues have been emitted by WriteModuleInfo. 2561 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 2562 if (!isa<GlobalValue>(Vals[i].first)) { 2563 writeConstants(i, Vals.size(), true); 2564 return; 2565 } 2566 } 2567 } 2568 2569 /// pushValueAndType - The file has to encode both the value and type id for 2570 /// many values, because we need to know what type to create for forward 2571 /// references. However, most operands are not forward references, so this type 2572 /// field is not needed. 2573 /// 2574 /// This function adds V's value ID to Vals. If the value ID is higher than the 2575 /// instruction ID, then it is a forward reference, and it also includes the 2576 /// type ID. The value ID that is written is encoded relative to the InstID. 2577 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID, 2578 SmallVectorImpl<unsigned> &Vals) { 2579 unsigned ValID = VE.getValueID(V); 2580 // Make encoding relative to the InstID. 2581 Vals.push_back(InstID - ValID); 2582 if (ValID >= InstID) { 2583 Vals.push_back(VE.getTypeID(V->getType())); 2584 return true; 2585 } 2586 return false; 2587 } 2588 2589 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS, 2590 unsigned InstID) { 2591 SmallVector<unsigned, 64> Record; 2592 LLVMContext &C = CS.getContext(); 2593 2594 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2595 const auto &Bundle = CS.getOperandBundleAt(i); 2596 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName())); 2597 2598 for (auto &Input : Bundle.Inputs) 2599 pushValueAndType(Input, InstID, Record); 2600 2601 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record); 2602 Record.clear(); 2603 } 2604 } 2605 2606 /// pushValue - Like pushValueAndType, but where the type of the value is 2607 /// omitted (perhaps it was already encoded in an earlier operand). 2608 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID, 2609 SmallVectorImpl<unsigned> &Vals) { 2610 unsigned ValID = VE.getValueID(V); 2611 Vals.push_back(InstID - ValID); 2612 } 2613 2614 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID, 2615 SmallVectorImpl<uint64_t> &Vals) { 2616 unsigned ValID = VE.getValueID(V); 2617 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 2618 emitSignedInt64(Vals, diff); 2619 } 2620 2621 /// WriteInstruction - Emit an instruction to the specified stream. 2622 void ModuleBitcodeWriter::writeInstruction(const Instruction &I, 2623 unsigned InstID, 2624 SmallVectorImpl<unsigned> &Vals) { 2625 unsigned Code = 0; 2626 unsigned AbbrevToUse = 0; 2627 VE.setInstructionID(&I); 2628 switch (I.getOpcode()) { 2629 default: 2630 if (Instruction::isCast(I.getOpcode())) { 2631 Code = bitc::FUNC_CODE_INST_CAST; 2632 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2633 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 2634 Vals.push_back(VE.getTypeID(I.getType())); 2635 Vals.push_back(getEncodedCastOpcode(I.getOpcode())); 2636 } else { 2637 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 2638 Code = bitc::FUNC_CODE_INST_BINOP; 2639 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2640 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 2641 pushValue(I.getOperand(1), InstID, Vals); 2642 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode())); 2643 uint64_t Flags = getOptimizationFlags(&I); 2644 if (Flags != 0) { 2645 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 2646 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 2647 Vals.push_back(Flags); 2648 } 2649 } 2650 break; 2651 case Instruction::FNeg: { 2652 Code = bitc::FUNC_CODE_INST_UNOP; 2653 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2654 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV; 2655 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode())); 2656 uint64_t Flags = getOptimizationFlags(&I); 2657 if (Flags != 0) { 2658 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV) 2659 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV; 2660 Vals.push_back(Flags); 2661 } 2662 break; 2663 } 2664 case Instruction::GetElementPtr: { 2665 Code = bitc::FUNC_CODE_INST_GEP; 2666 AbbrevToUse = FUNCTION_INST_GEP_ABBREV; 2667 auto &GEPInst = cast<GetElementPtrInst>(I); 2668 Vals.push_back(GEPInst.isInBounds()); 2669 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType())); 2670 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 2671 pushValueAndType(I.getOperand(i), InstID, Vals); 2672 break; 2673 } 2674 case Instruction::ExtractValue: { 2675 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 2676 pushValueAndType(I.getOperand(0), InstID, Vals); 2677 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 2678 Vals.append(EVI->idx_begin(), EVI->idx_end()); 2679 break; 2680 } 2681 case Instruction::InsertValue: { 2682 Code = bitc::FUNC_CODE_INST_INSERTVAL; 2683 pushValueAndType(I.getOperand(0), InstID, Vals); 2684 pushValueAndType(I.getOperand(1), InstID, Vals); 2685 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 2686 Vals.append(IVI->idx_begin(), IVI->idx_end()); 2687 break; 2688 } 2689 case Instruction::Select: { 2690 Code = bitc::FUNC_CODE_INST_VSELECT; 2691 pushValueAndType(I.getOperand(1), InstID, Vals); 2692 pushValue(I.getOperand(2), InstID, Vals); 2693 pushValueAndType(I.getOperand(0), InstID, Vals); 2694 uint64_t Flags = getOptimizationFlags(&I); 2695 if (Flags != 0) 2696 Vals.push_back(Flags); 2697 break; 2698 } 2699 case Instruction::ExtractElement: 2700 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 2701 pushValueAndType(I.getOperand(0), InstID, Vals); 2702 pushValueAndType(I.getOperand(1), InstID, Vals); 2703 break; 2704 case Instruction::InsertElement: 2705 Code = bitc::FUNC_CODE_INST_INSERTELT; 2706 pushValueAndType(I.getOperand(0), InstID, Vals); 2707 pushValue(I.getOperand(1), InstID, Vals); 2708 pushValueAndType(I.getOperand(2), InstID, Vals); 2709 break; 2710 case Instruction::ShuffleVector: 2711 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 2712 pushValueAndType(I.getOperand(0), InstID, Vals); 2713 pushValue(I.getOperand(1), InstID, Vals); 2714 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID, 2715 Vals); 2716 break; 2717 case Instruction::ICmp: 2718 case Instruction::FCmp: { 2719 // compare returning Int1Ty or vector of Int1Ty 2720 Code = bitc::FUNC_CODE_INST_CMP2; 2721 pushValueAndType(I.getOperand(0), InstID, Vals); 2722 pushValue(I.getOperand(1), InstID, Vals); 2723 Vals.push_back(cast<CmpInst>(I).getPredicate()); 2724 uint64_t Flags = getOptimizationFlags(&I); 2725 if (Flags != 0) 2726 Vals.push_back(Flags); 2727 break; 2728 } 2729 2730 case Instruction::Ret: 2731 { 2732 Code = bitc::FUNC_CODE_INST_RET; 2733 unsigned NumOperands = I.getNumOperands(); 2734 if (NumOperands == 0) 2735 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 2736 else if (NumOperands == 1) { 2737 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) 2738 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 2739 } else { 2740 for (unsigned i = 0, e = NumOperands; i != e; ++i) 2741 pushValueAndType(I.getOperand(i), InstID, Vals); 2742 } 2743 } 2744 break; 2745 case Instruction::Br: 2746 { 2747 Code = bitc::FUNC_CODE_INST_BR; 2748 const BranchInst &II = cast<BranchInst>(I); 2749 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 2750 if (II.isConditional()) { 2751 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 2752 pushValue(II.getCondition(), InstID, Vals); 2753 } 2754 } 2755 break; 2756 case Instruction::Switch: 2757 { 2758 Code = bitc::FUNC_CODE_INST_SWITCH; 2759 const SwitchInst &SI = cast<SwitchInst>(I); 2760 Vals.push_back(VE.getTypeID(SI.getCondition()->getType())); 2761 pushValue(SI.getCondition(), InstID, Vals); 2762 Vals.push_back(VE.getValueID(SI.getDefaultDest())); 2763 for (auto Case : SI.cases()) { 2764 Vals.push_back(VE.getValueID(Case.getCaseValue())); 2765 Vals.push_back(VE.getValueID(Case.getCaseSuccessor())); 2766 } 2767 } 2768 break; 2769 case Instruction::IndirectBr: 2770 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 2771 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2772 // Encode the address operand as relative, but not the basic blocks. 2773 pushValue(I.getOperand(0), InstID, Vals); 2774 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 2775 Vals.push_back(VE.getValueID(I.getOperand(i))); 2776 break; 2777 2778 case Instruction::Invoke: { 2779 const InvokeInst *II = cast<InvokeInst>(&I); 2780 const Value *Callee = II->getCalledOperand(); 2781 FunctionType *FTy = II->getFunctionType(); 2782 2783 if (II->hasOperandBundles()) 2784 writeOperandBundles(*II, InstID); 2785 2786 Code = bitc::FUNC_CODE_INST_INVOKE; 2787 2788 Vals.push_back(VE.getAttributeListID(II->getAttributes())); 2789 Vals.push_back(II->getCallingConv() | 1 << 13); 2790 Vals.push_back(VE.getValueID(II->getNormalDest())); 2791 Vals.push_back(VE.getValueID(II->getUnwindDest())); 2792 Vals.push_back(VE.getTypeID(FTy)); 2793 pushValueAndType(Callee, InstID, Vals); 2794 2795 // Emit value #'s for the fixed parameters. 2796 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2797 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2798 2799 // Emit type/value pairs for varargs params. 2800 if (FTy->isVarArg()) { 2801 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands(); 2802 i != e; ++i) 2803 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2804 } 2805 break; 2806 } 2807 case Instruction::Resume: 2808 Code = bitc::FUNC_CODE_INST_RESUME; 2809 pushValueAndType(I.getOperand(0), InstID, Vals); 2810 break; 2811 case Instruction::CleanupRet: { 2812 Code = bitc::FUNC_CODE_INST_CLEANUPRET; 2813 const auto &CRI = cast<CleanupReturnInst>(I); 2814 pushValue(CRI.getCleanupPad(), InstID, Vals); 2815 if (CRI.hasUnwindDest()) 2816 Vals.push_back(VE.getValueID(CRI.getUnwindDest())); 2817 break; 2818 } 2819 case Instruction::CatchRet: { 2820 Code = bitc::FUNC_CODE_INST_CATCHRET; 2821 const auto &CRI = cast<CatchReturnInst>(I); 2822 pushValue(CRI.getCatchPad(), InstID, Vals); 2823 Vals.push_back(VE.getValueID(CRI.getSuccessor())); 2824 break; 2825 } 2826 case Instruction::CleanupPad: 2827 case Instruction::CatchPad: { 2828 const auto &FuncletPad = cast<FuncletPadInst>(I); 2829 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD 2830 : bitc::FUNC_CODE_INST_CLEANUPPAD; 2831 pushValue(FuncletPad.getParentPad(), InstID, Vals); 2832 2833 unsigned NumArgOperands = FuncletPad.getNumArgOperands(); 2834 Vals.push_back(NumArgOperands); 2835 for (unsigned Op = 0; Op != NumArgOperands; ++Op) 2836 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals); 2837 break; 2838 } 2839 case Instruction::CatchSwitch: { 2840 Code = bitc::FUNC_CODE_INST_CATCHSWITCH; 2841 const auto &CatchSwitch = cast<CatchSwitchInst>(I); 2842 2843 pushValue(CatchSwitch.getParentPad(), InstID, Vals); 2844 2845 unsigned NumHandlers = CatchSwitch.getNumHandlers(); 2846 Vals.push_back(NumHandlers); 2847 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers()) 2848 Vals.push_back(VE.getValueID(CatchPadBB)); 2849 2850 if (CatchSwitch.hasUnwindDest()) 2851 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest())); 2852 break; 2853 } 2854 case Instruction::CallBr: { 2855 const CallBrInst *CBI = cast<CallBrInst>(&I); 2856 const Value *Callee = CBI->getCalledOperand(); 2857 FunctionType *FTy = CBI->getFunctionType(); 2858 2859 if (CBI->hasOperandBundles()) 2860 writeOperandBundles(*CBI, InstID); 2861 2862 Code = bitc::FUNC_CODE_INST_CALLBR; 2863 2864 Vals.push_back(VE.getAttributeListID(CBI->getAttributes())); 2865 2866 Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV | 2867 1 << bitc::CALL_EXPLICIT_TYPE); 2868 2869 Vals.push_back(VE.getValueID(CBI->getDefaultDest())); 2870 Vals.push_back(CBI->getNumIndirectDests()); 2871 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) 2872 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i))); 2873 2874 Vals.push_back(VE.getTypeID(FTy)); 2875 pushValueAndType(Callee, InstID, Vals); 2876 2877 // Emit value #'s for the fixed parameters. 2878 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2879 pushValue(I.getOperand(i), InstID, Vals); // fixed param. 2880 2881 // Emit type/value pairs for varargs params. 2882 if (FTy->isVarArg()) { 2883 for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands(); 2884 i != e; ++i) 2885 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg 2886 } 2887 break; 2888 } 2889 case Instruction::Unreachable: 2890 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 2891 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 2892 break; 2893 2894 case Instruction::PHI: { 2895 const PHINode &PN = cast<PHINode>(I); 2896 Code = bitc::FUNC_CODE_INST_PHI; 2897 // With the newer instruction encoding, forward references could give 2898 // negative valued IDs. This is most common for PHIs, so we use 2899 // signed VBRs. 2900 SmallVector<uint64_t, 128> Vals64; 2901 Vals64.push_back(VE.getTypeID(PN.getType())); 2902 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 2903 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64); 2904 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 2905 } 2906 2907 uint64_t Flags = getOptimizationFlags(&I); 2908 if (Flags != 0) 2909 Vals64.push_back(Flags); 2910 2911 // Emit a Vals64 vector and exit. 2912 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 2913 Vals64.clear(); 2914 return; 2915 } 2916 2917 case Instruction::LandingPad: { 2918 const LandingPadInst &LP = cast<LandingPadInst>(I); 2919 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 2920 Vals.push_back(VE.getTypeID(LP.getType())); 2921 Vals.push_back(LP.isCleanup()); 2922 Vals.push_back(LP.getNumClauses()); 2923 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 2924 if (LP.isCatch(I)) 2925 Vals.push_back(LandingPadInst::Catch); 2926 else 2927 Vals.push_back(LandingPadInst::Filter); 2928 pushValueAndType(LP.getClause(I), InstID, Vals); 2929 } 2930 break; 2931 } 2932 2933 case Instruction::Alloca: { 2934 Code = bitc::FUNC_CODE_INST_ALLOCA; 2935 const AllocaInst &AI = cast<AllocaInst>(I); 2936 Vals.push_back(VE.getTypeID(AI.getAllocatedType())); 2937 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 2938 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 2939 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1; 2940 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 && 2941 "not enough bits for maximum alignment"); 2942 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64"); 2943 AlignRecord |= AI.isUsedWithInAlloca() << 5; 2944 AlignRecord |= 1 << 6; 2945 AlignRecord |= AI.isSwiftError() << 7; 2946 Vals.push_back(AlignRecord); 2947 break; 2948 } 2949 2950 case Instruction::Load: 2951 if (cast<LoadInst>(I).isAtomic()) { 2952 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 2953 pushValueAndType(I.getOperand(0), InstID, Vals); 2954 } else { 2955 Code = bitc::FUNC_CODE_INST_LOAD; 2956 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr 2957 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 2958 } 2959 Vals.push_back(VE.getTypeID(I.getType())); 2960 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 2961 Vals.push_back(cast<LoadInst>(I).isVolatile()); 2962 if (cast<LoadInst>(I).isAtomic()) { 2963 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering())); 2964 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID())); 2965 } 2966 break; 2967 case Instruction::Store: 2968 if (cast<StoreInst>(I).isAtomic()) 2969 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 2970 else 2971 Code = bitc::FUNC_CODE_INST_STORE; 2972 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr 2973 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val 2974 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 2975 Vals.push_back(cast<StoreInst>(I).isVolatile()); 2976 if (cast<StoreInst>(I).isAtomic()) { 2977 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering())); 2978 Vals.push_back( 2979 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID())); 2980 } 2981 break; 2982 case Instruction::AtomicCmpXchg: 2983 Code = bitc::FUNC_CODE_INST_CMPXCHG; 2984 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2985 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp. 2986 pushValue(I.getOperand(2), InstID, Vals); // newval. 2987 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 2988 Vals.push_back( 2989 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering())); 2990 Vals.push_back( 2991 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID())); 2992 Vals.push_back( 2993 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering())); 2994 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak()); 2995 break; 2996 case Instruction::AtomicRMW: 2997 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 2998 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr 2999 pushValue(I.getOperand(1), InstID, Vals); // val. 3000 Vals.push_back( 3001 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation())); 3002 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 3003 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 3004 Vals.push_back( 3005 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID())); 3006 break; 3007 case Instruction::Fence: 3008 Code = bitc::FUNC_CODE_INST_FENCE; 3009 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering())); 3010 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID())); 3011 break; 3012 case Instruction::Call: { 3013 const CallInst &CI = cast<CallInst>(I); 3014 FunctionType *FTy = CI.getFunctionType(); 3015 3016 if (CI.hasOperandBundles()) 3017 writeOperandBundles(CI, InstID); 3018 3019 Code = bitc::FUNC_CODE_INST_CALL; 3020 3021 Vals.push_back(VE.getAttributeListID(CI.getAttributes())); 3022 3023 unsigned Flags = getOptimizationFlags(&I); 3024 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV | 3025 unsigned(CI.isTailCall()) << bitc::CALL_TAIL | 3026 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL | 3027 1 << bitc::CALL_EXPLICIT_TYPE | 3028 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL | 3029 unsigned(Flags != 0) << bitc::CALL_FMF); 3030 if (Flags != 0) 3031 Vals.push_back(Flags); 3032 3033 Vals.push_back(VE.getTypeID(FTy)); 3034 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee 3035 3036 // Emit value #'s for the fixed parameters. 3037 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3038 // Check for labels (can happen with asm labels). 3039 if (FTy->getParamType(i)->isLabelTy()) 3040 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 3041 else 3042 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param. 3043 } 3044 3045 // Emit type/value pairs for varargs params. 3046 if (FTy->isVarArg()) { 3047 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 3048 i != e; ++i) 3049 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs 3050 } 3051 break; 3052 } 3053 case Instruction::VAArg: 3054 Code = bitc::FUNC_CODE_INST_VAARG; 3055 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 3056 pushValue(I.getOperand(0), InstID, Vals); // valist. 3057 Vals.push_back(VE.getTypeID(I.getType())); // restype. 3058 break; 3059 case Instruction::Freeze: 3060 Code = bitc::FUNC_CODE_INST_FREEZE; 3061 pushValueAndType(I.getOperand(0), InstID, Vals); 3062 break; 3063 } 3064 3065 Stream.EmitRecord(Code, Vals, AbbrevToUse); 3066 Vals.clear(); 3067 } 3068 3069 /// Write a GlobalValue VST to the module. The purpose of this data structure is 3070 /// to allow clients to efficiently find the function body. 3071 void ModuleBitcodeWriter::writeGlobalValueSymbolTable( 3072 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3073 // Get the offset of the VST we are writing, and backpatch it into 3074 // the VST forward declaration record. 3075 uint64_t VSTOffset = Stream.GetCurrentBitNo(); 3076 // The BitcodeStartBit was the stream offset of the identification block. 3077 VSTOffset -= bitcodeStartBit(); 3078 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"); 3079 // Note that we add 1 here because the offset is relative to one word 3080 // before the start of the identification block, which was historically 3081 // always the start of the regular bitcode header. 3082 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1); 3083 3084 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3085 3086 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3087 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY)); 3088 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset 3090 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3091 3092 for (const Function &F : M) { 3093 uint64_t Record[2]; 3094 3095 if (F.isDeclaration()) 3096 continue; 3097 3098 Record[0] = VE.getValueID(&F); 3099 3100 // Save the word offset of the function (from the start of the 3101 // actual bitcode written to the stream). 3102 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit(); 3103 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"); 3104 // Note that we add 1 here because the offset is relative to one word 3105 // before the start of the identification block, which was historically 3106 // always the start of the regular bitcode header. 3107 Record[1] = BitcodeIndex / 32 + 1; 3108 3109 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev); 3110 } 3111 3112 Stream.ExitBlock(); 3113 } 3114 3115 /// Emit names for arguments, instructions and basic blocks in a function. 3116 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable( 3117 const ValueSymbolTable &VST) { 3118 if (VST.empty()) 3119 return; 3120 3121 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 3122 3123 // FIXME: Set up the abbrev, we know how many values there are! 3124 // FIXME: We know if the type names can use 7-bit ascii. 3125 SmallVector<uint64_t, 64> NameVals; 3126 3127 for (const ValueName &Name : VST) { 3128 // Figure out the encoding to use for the name. 3129 StringEncoding Bits = getStringEncoding(Name.getKey()); 3130 3131 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 3132 NameVals.push_back(VE.getValueID(Name.getValue())); 3133 3134 // VST_CODE_ENTRY: [valueid, namechar x N] 3135 // VST_CODE_BBENTRY: [bbid, namechar x N] 3136 unsigned Code; 3137 if (isa<BasicBlock>(Name.getValue())) { 3138 Code = bitc::VST_CODE_BBENTRY; 3139 if (Bits == SE_Char6) 3140 AbbrevToUse = VST_BBENTRY_6_ABBREV; 3141 } else { 3142 Code = bitc::VST_CODE_ENTRY; 3143 if (Bits == SE_Char6) 3144 AbbrevToUse = VST_ENTRY_6_ABBREV; 3145 else if (Bits == SE_Fixed7) 3146 AbbrevToUse = VST_ENTRY_7_ABBREV; 3147 } 3148 3149 for (const auto P : Name.getKey()) 3150 NameVals.push_back((unsigned char)P); 3151 3152 // Emit the finished record. 3153 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 3154 NameVals.clear(); 3155 } 3156 3157 Stream.ExitBlock(); 3158 } 3159 3160 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) { 3161 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3162 unsigned Code; 3163 if (isa<BasicBlock>(Order.V)) 3164 Code = bitc::USELIST_CODE_BB; 3165 else 3166 Code = bitc::USELIST_CODE_DEFAULT; 3167 3168 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end()); 3169 Record.push_back(VE.getValueID(Order.V)); 3170 Stream.EmitRecord(Code, Record); 3171 } 3172 3173 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) { 3174 assert(VE.shouldPreserveUseListOrder() && 3175 "Expected to be preserving use-list order"); 3176 3177 auto hasMore = [&]() { 3178 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F; 3179 }; 3180 if (!hasMore()) 3181 // Nothing to do. 3182 return; 3183 3184 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 3185 while (hasMore()) { 3186 writeUseList(std::move(VE.UseListOrders.back())); 3187 VE.UseListOrders.pop_back(); 3188 } 3189 Stream.ExitBlock(); 3190 } 3191 3192 /// Emit a function body to the module stream. 3193 void ModuleBitcodeWriter::writeFunction( 3194 const Function &F, 3195 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) { 3196 // Save the bitcode index of the start of this function block for recording 3197 // in the VST. 3198 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo(); 3199 3200 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 3201 VE.incorporateFunction(F); 3202 3203 SmallVector<unsigned, 64> Vals; 3204 3205 // Emit the number of basic blocks, so the reader can create them ahead of 3206 // time. 3207 Vals.push_back(VE.getBasicBlocks().size()); 3208 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 3209 Vals.clear(); 3210 3211 // If there are function-local constants, emit them now. 3212 unsigned CstStart, CstEnd; 3213 VE.getFunctionConstantRange(CstStart, CstEnd); 3214 writeConstants(CstStart, CstEnd, false); 3215 3216 // If there is function-local metadata, emit it now. 3217 writeFunctionMetadata(F); 3218 3219 // Keep a running idea of what the instruction ID is. 3220 unsigned InstID = CstEnd; 3221 3222 bool NeedsMetadataAttachment = F.hasMetadata(); 3223 3224 DILocation *LastDL = nullptr; 3225 // Finally, emit all the instructions, in order. 3226 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 3227 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 3228 I != E; ++I) { 3229 writeInstruction(*I, InstID, Vals); 3230 3231 if (!I->getType()->isVoidTy()) 3232 ++InstID; 3233 3234 // If the instruction has metadata, write a metadata attachment later. 3235 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 3236 3237 // If the instruction has a debug location, emit it. 3238 DILocation *DL = I->getDebugLoc(); 3239 if (!DL) 3240 continue; 3241 3242 if (DL == LastDL) { 3243 // Just repeat the same debug loc as last time. 3244 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 3245 continue; 3246 } 3247 3248 Vals.push_back(DL->getLine()); 3249 Vals.push_back(DL->getColumn()); 3250 Vals.push_back(VE.getMetadataOrNullID(DL->getScope())); 3251 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt())); 3252 Vals.push_back(DL->isImplicitCode()); 3253 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 3254 Vals.clear(); 3255 3256 LastDL = DL; 3257 } 3258 3259 // Emit names for all the instructions etc. 3260 if (auto *Symtab = F.getValueSymbolTable()) 3261 writeFunctionLevelValueSymbolTable(*Symtab); 3262 3263 if (NeedsMetadataAttachment) 3264 writeFunctionMetadataAttachment(F); 3265 if (VE.shouldPreserveUseListOrder()) 3266 writeUseListBlock(&F); 3267 VE.purgeFunction(); 3268 Stream.ExitBlock(); 3269 } 3270 3271 // Emit blockinfo, which defines the standard abbreviations etc. 3272 void ModuleBitcodeWriter::writeBlockInfo() { 3273 // We only want to emit block info records for blocks that have multiple 3274 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 3275 // Other blocks can define their abbrevs inline. 3276 Stream.EnterBlockInfoBlock(); 3277 3278 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings. 3279 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 3281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3284 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3285 VST_ENTRY_8_ABBREV) 3286 llvm_unreachable("Unexpected abbrev ordering!"); 3287 } 3288 3289 { // 7-bit fixed width VST_CODE_ENTRY strings. 3290 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3291 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3292 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3294 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3295 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3296 VST_ENTRY_7_ABBREV) 3297 llvm_unreachable("Unexpected abbrev ordering!"); 3298 } 3299 { // 6-bit char6 VST_CODE_ENTRY strings. 3300 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3301 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3305 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3306 VST_ENTRY_6_ABBREV) 3307 llvm_unreachable("Unexpected abbrev ordering!"); 3308 } 3309 { // 6-bit char6 VST_CODE_BBENTRY strings. 3310 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3311 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 3312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3315 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) != 3316 VST_BBENTRY_6_ABBREV) 3317 llvm_unreachable("Unexpected abbrev ordering!"); 3318 } 3319 3320 { // SETTYPE abbrev for CONSTANTS_BLOCK. 3321 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3322 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 3323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3324 VE.computeBitsRequiredForTypeIndicies())); 3325 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3326 CONSTANTS_SETTYPE_ABBREV) 3327 llvm_unreachable("Unexpected abbrev ordering!"); 3328 } 3329 3330 { // INTEGER abbrev for CONSTANTS_BLOCK. 3331 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3332 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 3333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3334 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3335 CONSTANTS_INTEGER_ABBREV) 3336 llvm_unreachable("Unexpected abbrev ordering!"); 3337 } 3338 3339 { // CE_CAST abbrev for CONSTANTS_BLOCK. 3340 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3341 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 3342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 3343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 3344 VE.computeBitsRequiredForTypeIndicies())); 3345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 3346 3347 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3348 CONSTANTS_CE_CAST_Abbrev) 3349 llvm_unreachable("Unexpected abbrev ordering!"); 3350 } 3351 { // NULL abbrev for CONSTANTS_BLOCK. 3352 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3353 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 3354 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) != 3355 CONSTANTS_NULL_Abbrev) 3356 llvm_unreachable("Unexpected abbrev ordering!"); 3357 } 3358 3359 // FIXME: This should only use space for first class types! 3360 3361 { // INST_LOAD abbrev for FUNCTION_BLOCK. 3362 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3363 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 3364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 3365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3366 VE.computeBitsRequiredForTypeIndicies())); 3367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 3368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 3369 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3370 FUNCTION_INST_LOAD_ABBREV) 3371 llvm_unreachable("Unexpected abbrev ordering!"); 3372 } 3373 { // INST_UNOP abbrev for FUNCTION_BLOCK. 3374 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3375 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3378 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3379 FUNCTION_INST_UNOP_ABBREV) 3380 llvm_unreachable("Unexpected abbrev ordering!"); 3381 } 3382 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK. 3383 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3384 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP)); 3385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3388 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3389 FUNCTION_INST_UNOP_FLAGS_ABBREV) 3390 llvm_unreachable("Unexpected abbrev ordering!"); 3391 } 3392 { // INST_BINOP abbrev for FUNCTION_BLOCK. 3393 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3394 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3398 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3399 FUNCTION_INST_BINOP_ABBREV) 3400 llvm_unreachable("Unexpected abbrev ordering!"); 3401 } 3402 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 3403 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3404 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 3405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 3406 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 3407 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3408 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags 3409 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3410 FUNCTION_INST_BINOP_FLAGS_ABBREV) 3411 llvm_unreachable("Unexpected abbrev ordering!"); 3412 } 3413 { // INST_CAST abbrev for FUNCTION_BLOCK. 3414 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3415 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 3416 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 3417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3418 VE.computeBitsRequiredForTypeIndicies())); 3419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 3420 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3421 FUNCTION_INST_CAST_ABBREV) 3422 llvm_unreachable("Unexpected abbrev ordering!"); 3423 } 3424 3425 { // INST_RET abbrev for FUNCTION_BLOCK. 3426 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3427 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3428 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3429 FUNCTION_INST_RET_VOID_ABBREV) 3430 llvm_unreachable("Unexpected abbrev ordering!"); 3431 } 3432 { // INST_RET abbrev for FUNCTION_BLOCK. 3433 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3434 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 3435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 3436 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3437 FUNCTION_INST_RET_VAL_ABBREV) 3438 llvm_unreachable("Unexpected abbrev ordering!"); 3439 } 3440 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 3441 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3442 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 3443 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3444 FUNCTION_INST_UNREACHABLE_ABBREV) 3445 llvm_unreachable("Unexpected abbrev ordering!"); 3446 } 3447 { 3448 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3449 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP)); 3450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); 3451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 3452 Log2_32_Ceil(VE.getTypes().size() + 1))); 3453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 3455 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) != 3456 FUNCTION_INST_GEP_ABBREV) 3457 llvm_unreachable("Unexpected abbrev ordering!"); 3458 } 3459 3460 Stream.ExitBlock(); 3461 } 3462 3463 /// Write the module path strings, currently only used when generating 3464 /// a combined index file. 3465 void IndexBitcodeWriter::writeModStrings() { 3466 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3); 3467 3468 // TODO: See which abbrev sizes we actually need to emit 3469 3470 // 8-bit fixed-width MST_ENTRY strings. 3471 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3472 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3474 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 3476 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv)); 3477 3478 // 7-bit fixed width MST_ENTRY strings. 3479 Abbv = std::make_shared<BitCodeAbbrev>(); 3480 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3481 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 3484 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv)); 3485 3486 // 6-bit char6 MST_ENTRY strings. 3487 Abbv = std::make_shared<BitCodeAbbrev>(); 3488 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY)); 3489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3490 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3491 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 3492 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv)); 3493 3494 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY. 3495 Abbv = std::make_shared<BitCodeAbbrev>(); 3496 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH)); 3497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3499 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3501 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3502 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv)); 3503 3504 SmallVector<unsigned, 64> Vals; 3505 forEachModule( 3506 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) { 3507 StringRef Key = MPSE.getKey(); 3508 const auto &Value = MPSE.getValue(); 3509 StringEncoding Bits = getStringEncoding(Key); 3510 unsigned AbbrevToUse = Abbrev8Bit; 3511 if (Bits == SE_Char6) 3512 AbbrevToUse = Abbrev6Bit; 3513 else if (Bits == SE_Fixed7) 3514 AbbrevToUse = Abbrev7Bit; 3515 3516 Vals.push_back(Value.first); 3517 Vals.append(Key.begin(), Key.end()); 3518 3519 // Emit the finished record. 3520 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse); 3521 3522 // Emit an optional hash for the module now 3523 const auto &Hash = Value.second; 3524 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) { 3525 Vals.assign(Hash.begin(), Hash.end()); 3526 // Emit the hash record. 3527 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash); 3528 } 3529 3530 Vals.clear(); 3531 }); 3532 Stream.ExitBlock(); 3533 } 3534 3535 /// Write the function type metadata related records that need to appear before 3536 /// a function summary entry (whether per-module or combined). 3537 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, 3538 FunctionSummary *FS) { 3539 if (!FS->type_tests().empty()) 3540 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests()); 3541 3542 SmallVector<uint64_t, 64> Record; 3543 3544 auto WriteVFuncIdVec = [&](uint64_t Ty, 3545 ArrayRef<FunctionSummary::VFuncId> VFs) { 3546 if (VFs.empty()) 3547 return; 3548 Record.clear(); 3549 for (auto &VF : VFs) { 3550 Record.push_back(VF.GUID); 3551 Record.push_back(VF.Offset); 3552 } 3553 Stream.EmitRecord(Ty, Record); 3554 }; 3555 3556 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS, 3557 FS->type_test_assume_vcalls()); 3558 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS, 3559 FS->type_checked_load_vcalls()); 3560 3561 auto WriteConstVCallVec = [&](uint64_t Ty, 3562 ArrayRef<FunctionSummary::ConstVCall> VCs) { 3563 for (auto &VC : VCs) { 3564 Record.clear(); 3565 Record.push_back(VC.VFunc.GUID); 3566 Record.push_back(VC.VFunc.Offset); 3567 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end()); 3568 Stream.EmitRecord(Ty, Record); 3569 } 3570 }; 3571 3572 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL, 3573 FS->type_test_assume_const_vcalls()); 3574 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL, 3575 FS->type_checked_load_const_vcalls()); 3576 } 3577 3578 /// Collect type IDs from type tests used by function. 3579 static void 3580 getReferencedTypeIds(FunctionSummary *FS, 3581 std::set<GlobalValue::GUID> &ReferencedTypeIds) { 3582 if (!FS->type_tests().empty()) 3583 for (auto &TT : FS->type_tests()) 3584 ReferencedTypeIds.insert(TT); 3585 3586 auto GetReferencedTypesFromVFuncIdVec = 3587 [&](ArrayRef<FunctionSummary::VFuncId> VFs) { 3588 for (auto &VF : VFs) 3589 ReferencedTypeIds.insert(VF.GUID); 3590 }; 3591 3592 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls()); 3593 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls()); 3594 3595 auto GetReferencedTypesFromConstVCallVec = 3596 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) { 3597 for (auto &VC : VCs) 3598 ReferencedTypeIds.insert(VC.VFunc.GUID); 3599 }; 3600 3601 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls()); 3602 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls()); 3603 } 3604 3605 static void writeWholeProgramDevirtResolutionByArg( 3606 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args, 3607 const WholeProgramDevirtResolution::ByArg &ByArg) { 3608 NameVals.push_back(args.size()); 3609 NameVals.insert(NameVals.end(), args.begin(), args.end()); 3610 3611 NameVals.push_back(ByArg.TheKind); 3612 NameVals.push_back(ByArg.Info); 3613 NameVals.push_back(ByArg.Byte); 3614 NameVals.push_back(ByArg.Bit); 3615 } 3616 3617 static void writeWholeProgramDevirtResolution( 3618 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 3619 uint64_t Id, const WholeProgramDevirtResolution &Wpd) { 3620 NameVals.push_back(Id); 3621 3622 NameVals.push_back(Wpd.TheKind); 3623 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName)); 3624 NameVals.push_back(Wpd.SingleImplName.size()); 3625 3626 NameVals.push_back(Wpd.ResByArg.size()); 3627 for (auto &A : Wpd.ResByArg) 3628 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second); 3629 } 3630 3631 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals, 3632 StringTableBuilder &StrtabBuilder, 3633 const std::string &Id, 3634 const TypeIdSummary &Summary) { 3635 NameVals.push_back(StrtabBuilder.add(Id)); 3636 NameVals.push_back(Id.size()); 3637 3638 NameVals.push_back(Summary.TTRes.TheKind); 3639 NameVals.push_back(Summary.TTRes.SizeM1BitWidth); 3640 NameVals.push_back(Summary.TTRes.AlignLog2); 3641 NameVals.push_back(Summary.TTRes.SizeM1); 3642 NameVals.push_back(Summary.TTRes.BitMask); 3643 NameVals.push_back(Summary.TTRes.InlineBits); 3644 3645 for (auto &W : Summary.WPDRes) 3646 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first, 3647 W.second); 3648 } 3649 3650 static void writeTypeIdCompatibleVtableSummaryRecord( 3651 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder, 3652 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary, 3653 ValueEnumerator &VE) { 3654 NameVals.push_back(StrtabBuilder.add(Id)); 3655 NameVals.push_back(Id.size()); 3656 3657 for (auto &P : Summary) { 3658 NameVals.push_back(P.AddressPointOffset); 3659 NameVals.push_back(VE.getValueID(P.VTableVI.getValue())); 3660 } 3661 } 3662 3663 // Helper to emit a single function summary record. 3664 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord( 3665 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary, 3666 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev, 3667 const Function &F) { 3668 NameVals.push_back(ValueID); 3669 3670 FunctionSummary *FS = cast<FunctionSummary>(Summary); 3671 writeFunctionTypeMetadataRecords(Stream, FS); 3672 3673 auto SpecialRefCnts = FS->specialRefCounts(); 3674 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 3675 NameVals.push_back(FS->instCount()); 3676 NameVals.push_back(getEncodedFFlags(FS->fflags())); 3677 NameVals.push_back(FS->refs().size()); 3678 NameVals.push_back(SpecialRefCnts.first); // rorefcnt 3679 NameVals.push_back(SpecialRefCnts.second); // worefcnt 3680 3681 for (auto &RI : FS->refs()) 3682 NameVals.push_back(VE.getValueID(RI.getValue())); 3683 3684 bool HasProfileData = 3685 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None; 3686 for (auto &ECI : FS->calls()) { 3687 NameVals.push_back(getValueId(ECI.first)); 3688 if (HasProfileData) 3689 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness)); 3690 else if (WriteRelBFToSummary) 3691 NameVals.push_back(ECI.second.RelBlockFreq); 3692 } 3693 3694 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 3695 unsigned Code = 3696 (HasProfileData ? bitc::FS_PERMODULE_PROFILE 3697 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF 3698 : bitc::FS_PERMODULE)); 3699 3700 // Emit the finished record. 3701 Stream.EmitRecord(Code, NameVals, FSAbbrev); 3702 NameVals.clear(); 3703 } 3704 3705 // Collect the global value references in the given variable's initializer, 3706 // and emit them in a summary record. 3707 void ModuleBitcodeWriterBase::writeModuleLevelReferences( 3708 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals, 3709 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) { 3710 auto VI = Index->getValueInfo(V.getGUID()); 3711 if (!VI || VI.getSummaryList().empty()) { 3712 // Only declarations should not have a summary (a declaration might however 3713 // have a summary if the def was in module level asm). 3714 assert(V.isDeclaration()); 3715 return; 3716 } 3717 auto *Summary = VI.getSummaryList()[0].get(); 3718 NameVals.push_back(VE.getValueID(&V)); 3719 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary); 3720 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 3721 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 3722 3723 auto VTableFuncs = VS->vTableFuncs(); 3724 if (!VTableFuncs.empty()) 3725 NameVals.push_back(VS->refs().size()); 3726 3727 unsigned SizeBeforeRefs = NameVals.size(); 3728 for (auto &RI : VS->refs()) 3729 NameVals.push_back(VE.getValueID(RI.getValue())); 3730 // Sort the refs for determinism output, the vector returned by FS->refs() has 3731 // been initialized from a DenseSet. 3732 llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end()); 3733 3734 if (VTableFuncs.empty()) 3735 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals, 3736 FSModRefsAbbrev); 3737 else { 3738 // VTableFuncs pairs should already be sorted by offset. 3739 for (auto &P : VTableFuncs) { 3740 NameVals.push_back(VE.getValueID(P.FuncVI.getValue())); 3741 NameVals.push_back(P.VTableOffset); 3742 } 3743 3744 Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals, 3745 FSModVTableRefsAbbrev); 3746 } 3747 NameVals.clear(); 3748 } 3749 3750 /// Emit the per-module summary section alongside the rest of 3751 /// the module's bitcode. 3752 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() { 3753 // By default we compile with ThinLTO if the module has a summary, but the 3754 // client can request full LTO with a module flag. 3755 bool IsThinLTO = true; 3756 if (auto *MD = 3757 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO"))) 3758 IsThinLTO = MD->getZExtValue(); 3759 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID 3760 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID, 3761 4); 3762 3763 Stream.EmitRecord( 3764 bitc::FS_VERSION, 3765 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 3766 3767 // Write the index flags. 3768 uint64_t Flags = 0; 3769 // Bits 1-3 are set only in the combined index, skip them. 3770 if (Index->enableSplitLTOUnit()) 3771 Flags |= 0x8; 3772 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags}); 3773 3774 if (Index->begin() == Index->end()) { 3775 Stream.ExitBlock(); 3776 return; 3777 } 3778 3779 for (const auto &GVI : valueIds()) { 3780 Stream.EmitRecord(bitc::FS_VALUE_GUID, 3781 ArrayRef<uint64_t>{GVI.second, GVI.first}); 3782 } 3783 3784 // Abbrev for FS_PERMODULE_PROFILE. 3785 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3786 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE)); 3787 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3788 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3794 // numrefs x valueid, n x (valueid, hotness) 3795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3797 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3798 3799 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF. 3800 Abbv = std::make_shared<BitCodeAbbrev>(); 3801 if (WriteRelBFToSummary) 3802 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF)); 3803 else 3804 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE)); 3805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3811 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3812 // numrefs x valueid, n x (valueid [, rel_block_freq]) 3813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3815 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3816 3817 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS. 3818 Abbv = std::make_shared<BitCodeAbbrev>(); 3819 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS)); 3820 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 3823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3824 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3825 3826 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS. 3827 Abbv = std::make_shared<BitCodeAbbrev>(); 3828 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)); 3829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3832 // numrefs x valueid, n x (valueid , offset) 3833 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3835 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3836 3837 // Abbrev for FS_ALIAS. 3838 Abbv = std::make_shared<BitCodeAbbrev>(); 3839 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS)); 3840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3842 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3843 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3844 3845 // Abbrev for FS_TYPE_ID_METADATA 3846 Abbv = std::make_shared<BitCodeAbbrev>(); 3847 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA)); 3848 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index 3849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length 3850 // n x (valueid , offset) 3851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3853 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3854 3855 SmallVector<uint64_t, 64> NameVals; 3856 // Iterate over the list of functions instead of the Index to 3857 // ensure the ordering is stable. 3858 for (const Function &F : M) { 3859 // Summary emission does not support anonymous functions, they have to 3860 // renamed using the anonymous function renaming pass. 3861 if (!F.hasName()) 3862 report_fatal_error("Unexpected anonymous function when writing summary"); 3863 3864 ValueInfo VI = Index->getValueInfo(F.getGUID()); 3865 if (!VI || VI.getSummaryList().empty()) { 3866 // Only declarations should not have a summary (a declaration might 3867 // however have a summary if the def was in module level asm). 3868 assert(F.isDeclaration()); 3869 continue; 3870 } 3871 auto *Summary = VI.getSummaryList()[0].get(); 3872 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F), 3873 FSCallsAbbrev, FSCallsProfileAbbrev, F); 3874 } 3875 3876 // Capture references from GlobalVariable initializers, which are outside 3877 // of a function scope. 3878 for (const GlobalVariable &G : M.globals()) 3879 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev, 3880 FSModVTableRefsAbbrev); 3881 3882 for (const GlobalAlias &A : M.aliases()) { 3883 auto *Aliasee = A.getBaseObject(); 3884 if (!Aliasee->hasName()) 3885 // Nameless function don't have an entry in the summary, skip it. 3886 continue; 3887 auto AliasId = VE.getValueID(&A); 3888 auto AliaseeId = VE.getValueID(Aliasee); 3889 NameVals.push_back(AliasId); 3890 auto *Summary = Index->getGlobalValueSummary(A); 3891 AliasSummary *AS = cast<AliasSummary>(Summary); 3892 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 3893 NameVals.push_back(AliaseeId); 3894 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev); 3895 NameVals.clear(); 3896 } 3897 3898 for (auto &S : Index->typeIdCompatibleVtableMap()) { 3899 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first, 3900 S.second, VE); 3901 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals, 3902 TypeIdCompatibleVtableAbbrev); 3903 NameVals.clear(); 3904 } 3905 3906 Stream.ExitBlock(); 3907 } 3908 3909 /// Emit the combined summary section into the combined index file. 3910 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() { 3911 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3); 3912 Stream.EmitRecord( 3913 bitc::FS_VERSION, 3914 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion}); 3915 3916 // Write the index flags. 3917 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()}); 3918 3919 for (const auto &GVI : valueIds()) { 3920 Stream.EmitRecord(bitc::FS_VALUE_GUID, 3921 ArrayRef<uint64_t>{GVI.second, GVI.first}); 3922 } 3923 3924 // Abbrev for FS_COMBINED. 3925 auto Abbv = std::make_shared<BitCodeAbbrev>(); 3926 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED)); 3927 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3928 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 3933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3935 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3936 // numrefs x valueid, n x (valueid) 3937 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3938 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3939 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3940 3941 // Abbrev for FS_COMBINED_PROFILE. 3942 Abbv = std::make_shared<BitCodeAbbrev>(); 3943 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE)); 3944 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount 3948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags 3949 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount 3950 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs 3951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt 3952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt 3953 // numrefs x valueid, n x (valueid, hotness) 3954 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 3955 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3956 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3957 3958 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS. 3959 Abbv = std::make_shared<BitCodeAbbrev>(); 3960 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS)); 3961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids 3965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 3966 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3967 3968 // Abbrev for FS_COMBINED_ALIAS. 3969 Abbv = std::make_shared<BitCodeAbbrev>(); 3970 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS)); 3971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid 3973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags 3974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid 3975 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 3976 3977 // The aliases are emitted as a post-pass, and will point to the value 3978 // id of the aliasee. Save them in a vector for post-processing. 3979 SmallVector<AliasSummary *, 64> Aliases; 3980 3981 // Save the value id for each summary for alias emission. 3982 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap; 3983 3984 SmallVector<uint64_t, 64> NameVals; 3985 3986 // Set that will be populated during call to writeFunctionTypeMetadataRecords 3987 // with the type ids referenced by this index file. 3988 std::set<GlobalValue::GUID> ReferencedTypeIds; 3989 3990 // For local linkage, we also emit the original name separately 3991 // immediately after the record. 3992 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) { 3993 if (!GlobalValue::isLocalLinkage(S.linkage())) 3994 return; 3995 NameVals.push_back(S.getOriginalName()); 3996 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals); 3997 NameVals.clear(); 3998 }; 3999 4000 std::set<GlobalValue::GUID> DefOrUseGUIDs; 4001 forEachSummary([&](GVInfo I, bool IsAliasee) { 4002 GlobalValueSummary *S = I.second; 4003 assert(S); 4004 DefOrUseGUIDs.insert(I.first); 4005 for (const ValueInfo &VI : S->refs()) 4006 DefOrUseGUIDs.insert(VI.getGUID()); 4007 4008 auto ValueId = getValueId(I.first); 4009 assert(ValueId); 4010 SummaryToValueIdMap[S] = *ValueId; 4011 4012 // If this is invoked for an aliasee, we want to record the above 4013 // mapping, but then not emit a summary entry (if the aliasee is 4014 // to be imported, we will invoke this separately with IsAliasee=false). 4015 if (IsAliasee) 4016 return; 4017 4018 if (auto *AS = dyn_cast<AliasSummary>(S)) { 4019 // Will process aliases as a post-pass because the reader wants all 4020 // global to be loaded first. 4021 Aliases.push_back(AS); 4022 return; 4023 } 4024 4025 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) { 4026 NameVals.push_back(*ValueId); 4027 NameVals.push_back(Index.getModuleId(VS->modulePath())); 4028 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags())); 4029 NameVals.push_back(getEncodedGVarFlags(VS->varflags())); 4030 for (auto &RI : VS->refs()) { 4031 auto RefValueId = getValueId(RI.getGUID()); 4032 if (!RefValueId) 4033 continue; 4034 NameVals.push_back(*RefValueId); 4035 } 4036 4037 // Emit the finished record. 4038 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals, 4039 FSModRefsAbbrev); 4040 NameVals.clear(); 4041 MaybeEmitOriginalName(*S); 4042 return; 4043 } 4044 4045 auto *FS = cast<FunctionSummary>(S); 4046 writeFunctionTypeMetadataRecords(Stream, FS); 4047 getReferencedTypeIds(FS, ReferencedTypeIds); 4048 4049 NameVals.push_back(*ValueId); 4050 NameVals.push_back(Index.getModuleId(FS->modulePath())); 4051 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags())); 4052 NameVals.push_back(FS->instCount()); 4053 NameVals.push_back(getEncodedFFlags(FS->fflags())); 4054 NameVals.push_back(FS->entryCount()); 4055 4056 // Fill in below 4057 NameVals.push_back(0); // numrefs 4058 NameVals.push_back(0); // rorefcnt 4059 NameVals.push_back(0); // worefcnt 4060 4061 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0; 4062 for (auto &RI : FS->refs()) { 4063 auto RefValueId = getValueId(RI.getGUID()); 4064 if (!RefValueId) 4065 continue; 4066 NameVals.push_back(*RefValueId); 4067 if (RI.isReadOnly()) 4068 RORefCnt++; 4069 else if (RI.isWriteOnly()) 4070 WORefCnt++; 4071 Count++; 4072 } 4073 NameVals[6] = Count; 4074 NameVals[7] = RORefCnt; 4075 NameVals[8] = WORefCnt; 4076 4077 bool HasProfileData = false; 4078 for (auto &EI : FS->calls()) { 4079 HasProfileData |= 4080 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown; 4081 if (HasProfileData) 4082 break; 4083 } 4084 4085 for (auto &EI : FS->calls()) { 4086 // If this GUID doesn't have a value id, it doesn't have a function 4087 // summary and we don't need to record any calls to it. 4088 GlobalValue::GUID GUID = EI.first.getGUID(); 4089 auto CallValueId = getValueId(GUID); 4090 if (!CallValueId) { 4091 // For SamplePGO, the indirect call targets for local functions will 4092 // have its original name annotated in profile. We try to find the 4093 // corresponding PGOFuncName as the GUID. 4094 GUID = Index.getGUIDFromOriginalID(GUID); 4095 if (GUID == 0) 4096 continue; 4097 CallValueId = getValueId(GUID); 4098 if (!CallValueId) 4099 continue; 4100 // The mapping from OriginalId to GUID may return a GUID 4101 // that corresponds to a static variable. Filter it out here. 4102 // This can happen when 4103 // 1) There is a call to a library function which does not have 4104 // a CallValidId; 4105 // 2) There is a static variable with the OriginalGUID identical 4106 // to the GUID of the library function in 1); 4107 // When this happens, the logic for SamplePGO kicks in and 4108 // the static variable in 2) will be found, which needs to be 4109 // filtered out. 4110 auto *GVSum = Index.getGlobalValueSummary(GUID, false); 4111 if (GVSum && 4112 GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind) 4113 continue; 4114 } 4115 NameVals.push_back(*CallValueId); 4116 if (HasProfileData) 4117 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness)); 4118 } 4119 4120 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev); 4121 unsigned Code = 4122 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED); 4123 4124 // Emit the finished record. 4125 Stream.EmitRecord(Code, NameVals, FSAbbrev); 4126 NameVals.clear(); 4127 MaybeEmitOriginalName(*S); 4128 }); 4129 4130 for (auto *AS : Aliases) { 4131 auto AliasValueId = SummaryToValueIdMap[AS]; 4132 assert(AliasValueId); 4133 NameVals.push_back(AliasValueId); 4134 NameVals.push_back(Index.getModuleId(AS->modulePath())); 4135 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags())); 4136 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()]; 4137 assert(AliaseeValueId); 4138 NameVals.push_back(AliaseeValueId); 4139 4140 // Emit the finished record. 4141 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev); 4142 NameVals.clear(); 4143 MaybeEmitOriginalName(*AS); 4144 4145 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee())) 4146 getReferencedTypeIds(FS, ReferencedTypeIds); 4147 } 4148 4149 if (!Index.cfiFunctionDefs().empty()) { 4150 for (auto &S : Index.cfiFunctionDefs()) { 4151 if (DefOrUseGUIDs.count( 4152 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4153 NameVals.push_back(StrtabBuilder.add(S)); 4154 NameVals.push_back(S.size()); 4155 } 4156 } 4157 if (!NameVals.empty()) { 4158 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals); 4159 NameVals.clear(); 4160 } 4161 } 4162 4163 if (!Index.cfiFunctionDecls().empty()) { 4164 for (auto &S : Index.cfiFunctionDecls()) { 4165 if (DefOrUseGUIDs.count( 4166 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) { 4167 NameVals.push_back(StrtabBuilder.add(S)); 4168 NameVals.push_back(S.size()); 4169 } 4170 } 4171 if (!NameVals.empty()) { 4172 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals); 4173 NameVals.clear(); 4174 } 4175 } 4176 4177 // Walk the GUIDs that were referenced, and write the 4178 // corresponding type id records. 4179 for (auto &T : ReferencedTypeIds) { 4180 auto TidIter = Index.typeIds().equal_range(T); 4181 for (auto It = TidIter.first; It != TidIter.second; ++It) { 4182 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first, 4183 It->second.second); 4184 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals); 4185 NameVals.clear(); 4186 } 4187 } 4188 4189 Stream.ExitBlock(); 4190 } 4191 4192 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the 4193 /// current llvm version, and a record for the epoch number. 4194 static void writeIdentificationBlock(BitstreamWriter &Stream) { 4195 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5); 4196 4197 // Write the "user readable" string identifying the bitcode producer 4198 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4199 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING)); 4200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 4202 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4203 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING, 4204 "LLVM" LLVM_VERSION_STRING, StringAbbrev); 4205 4206 // Write the epoch version 4207 Abbv = std::make_shared<BitCodeAbbrev>(); 4208 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH)); 4209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); 4210 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4211 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}}; 4212 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev); 4213 Stream.ExitBlock(); 4214 } 4215 4216 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) { 4217 // Emit the module's hash. 4218 // MODULE_CODE_HASH: [5*i32] 4219 if (GenerateHash) { 4220 uint32_t Vals[5]; 4221 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos], 4222 Buffer.size() - BlockStartPos)); 4223 StringRef Hash = Hasher.result(); 4224 for (int Pos = 0; Pos < 20; Pos += 4) { 4225 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos); 4226 } 4227 4228 // Emit the finished record. 4229 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals); 4230 4231 if (ModHash) 4232 // Save the written hash value. 4233 llvm::copy(Vals, std::begin(*ModHash)); 4234 } 4235 } 4236 4237 void ModuleBitcodeWriter::write() { 4238 writeIdentificationBlock(Stream); 4239 4240 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4241 size_t BlockStartPos = Buffer.size(); 4242 4243 writeModuleVersion(); 4244 4245 // Emit blockinfo, which defines the standard abbreviations etc. 4246 writeBlockInfo(); 4247 4248 // Emit information describing all of the types in the module. 4249 writeTypeTable(); 4250 4251 // Emit information about attribute groups. 4252 writeAttributeGroupTable(); 4253 4254 // Emit information about parameter attributes. 4255 writeAttributeTable(); 4256 4257 writeComdats(); 4258 4259 // Emit top-level description of module, including target triple, inline asm, 4260 // descriptors for global variables, and function prototype info. 4261 writeModuleInfo(); 4262 4263 // Emit constants. 4264 writeModuleConstants(); 4265 4266 // Emit metadata kind names. 4267 writeModuleMetadataKinds(); 4268 4269 // Emit metadata. 4270 writeModuleMetadata(); 4271 4272 // Emit module-level use-lists. 4273 if (VE.shouldPreserveUseListOrder()) 4274 writeUseListBlock(nullptr); 4275 4276 writeOperandBundleTags(); 4277 writeSyncScopeNames(); 4278 4279 // Emit function bodies. 4280 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex; 4281 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F) 4282 if (!F->isDeclaration()) 4283 writeFunction(*F, FunctionToBitcodeIndex); 4284 4285 // Need to write after the above call to WriteFunction which populates 4286 // the summary information in the index. 4287 if (Index) 4288 writePerModuleGlobalValueSummary(); 4289 4290 writeGlobalValueSymbolTable(FunctionToBitcodeIndex); 4291 4292 writeModuleHash(BlockStartPos); 4293 4294 Stream.ExitBlock(); 4295 } 4296 4297 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 4298 uint32_t &Position) { 4299 support::endian::write32le(&Buffer[Position], Value); 4300 Position += 4; 4301 } 4302 4303 /// If generating a bc file on darwin, we have to emit a 4304 /// header and trailer to make it compatible with the system archiver. To do 4305 /// this we emit the following header, and then emit a trailer that pads the 4306 /// file out to be a multiple of 16 bytes. 4307 /// 4308 /// struct bc_header { 4309 /// uint32_t Magic; // 0x0B17C0DE 4310 /// uint32_t Version; // Version, currently always 0. 4311 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 4312 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 4313 /// uint32_t CPUType; // CPU specifier. 4314 /// ... potentially more later ... 4315 /// }; 4316 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 4317 const Triple &TT) { 4318 unsigned CPUType = ~0U; 4319 4320 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 4321 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 4322 // number from /usr/include/mach/machine.h. It is ok to reproduce the 4323 // specific constants here because they are implicitly part of the Darwin ABI. 4324 enum { 4325 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 4326 DARWIN_CPU_TYPE_X86 = 7, 4327 DARWIN_CPU_TYPE_ARM = 12, 4328 DARWIN_CPU_TYPE_POWERPC = 18 4329 }; 4330 4331 Triple::ArchType Arch = TT.getArch(); 4332 if (Arch == Triple::x86_64) 4333 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 4334 else if (Arch == Triple::x86) 4335 CPUType = DARWIN_CPU_TYPE_X86; 4336 else if (Arch == Triple::ppc) 4337 CPUType = DARWIN_CPU_TYPE_POWERPC; 4338 else if (Arch == Triple::ppc64) 4339 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 4340 else if (Arch == Triple::arm || Arch == Triple::thumb) 4341 CPUType = DARWIN_CPU_TYPE_ARM; 4342 4343 // Traditional Bitcode starts after header. 4344 assert(Buffer.size() >= BWH_HeaderSize && 4345 "Expected header size to be reserved"); 4346 unsigned BCOffset = BWH_HeaderSize; 4347 unsigned BCSize = Buffer.size() - BWH_HeaderSize; 4348 4349 // Write the magic and version. 4350 unsigned Position = 0; 4351 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position); 4352 writeInt32ToBuffer(0, Buffer, Position); // Version. 4353 writeInt32ToBuffer(BCOffset, Buffer, Position); 4354 writeInt32ToBuffer(BCSize, Buffer, Position); 4355 writeInt32ToBuffer(CPUType, Buffer, Position); 4356 4357 // If the file is not a multiple of 16 bytes, insert dummy padding. 4358 while (Buffer.size() & 15) 4359 Buffer.push_back(0); 4360 } 4361 4362 /// Helper to write the header common to all bitcode files. 4363 static void writeBitcodeHeader(BitstreamWriter &Stream) { 4364 // Emit the file header. 4365 Stream.Emit((unsigned)'B', 8); 4366 Stream.Emit((unsigned)'C', 8); 4367 Stream.Emit(0x0, 4); 4368 Stream.Emit(0xC, 4); 4369 Stream.Emit(0xE, 4); 4370 Stream.Emit(0xD, 4); 4371 } 4372 4373 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer) 4374 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) { 4375 writeBitcodeHeader(*Stream); 4376 } 4377 4378 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); } 4379 4380 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) { 4381 Stream->EnterSubblock(Block, 3); 4382 4383 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4384 Abbv->Add(BitCodeAbbrevOp(Record)); 4385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4386 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv)); 4387 4388 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob); 4389 4390 Stream->ExitBlock(); 4391 } 4392 4393 void BitcodeWriter::writeSymtab() { 4394 assert(!WroteStrtab && !WroteSymtab); 4395 4396 // If any module has module-level inline asm, we will require a registered asm 4397 // parser for the target so that we can create an accurate symbol table for 4398 // the module. 4399 for (Module *M : Mods) { 4400 if (M->getModuleInlineAsm().empty()) 4401 continue; 4402 4403 std::string Err; 4404 const Triple TT(M->getTargetTriple()); 4405 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err); 4406 if (!T || !T->hasMCAsmParser()) 4407 return; 4408 } 4409 4410 WroteSymtab = true; 4411 SmallVector<char, 0> Symtab; 4412 // The irsymtab::build function may be unable to create a symbol table if the 4413 // module is malformed (e.g. it contains an invalid alias). Writing a symbol 4414 // table is not required for correctness, but we still want to be able to 4415 // write malformed modules to bitcode files, so swallow the error. 4416 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) { 4417 consumeError(std::move(E)); 4418 return; 4419 } 4420 4421 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB, 4422 {Symtab.data(), Symtab.size()}); 4423 } 4424 4425 void BitcodeWriter::writeStrtab() { 4426 assert(!WroteStrtab); 4427 4428 std::vector<char> Strtab; 4429 StrtabBuilder.finalizeInOrder(); 4430 Strtab.resize(StrtabBuilder.getSize()); 4431 StrtabBuilder.write((uint8_t *)Strtab.data()); 4432 4433 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, 4434 {Strtab.data(), Strtab.size()}); 4435 4436 WroteStrtab = true; 4437 } 4438 4439 void BitcodeWriter::copyStrtab(StringRef Strtab) { 4440 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab); 4441 WroteStrtab = true; 4442 } 4443 4444 void BitcodeWriter::writeModule(const Module &M, 4445 bool ShouldPreserveUseListOrder, 4446 const ModuleSummaryIndex *Index, 4447 bool GenerateHash, ModuleHash *ModHash) { 4448 assert(!WroteStrtab); 4449 4450 // The Mods vector is used by irsymtab::build, which requires non-const 4451 // Modules in case it needs to materialize metadata. But the bitcode writer 4452 // requires that the module is materialized, so we can cast to non-const here, 4453 // after checking that it is in fact materialized. 4454 assert(M.isMaterialized()); 4455 Mods.push_back(const_cast<Module *>(&M)); 4456 4457 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream, 4458 ShouldPreserveUseListOrder, Index, 4459 GenerateHash, ModHash); 4460 ModuleWriter.write(); 4461 } 4462 4463 void BitcodeWriter::writeIndex( 4464 const ModuleSummaryIndex *Index, 4465 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 4466 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, 4467 ModuleToSummariesForIndex); 4468 IndexWriter.write(); 4469 } 4470 4471 /// Write the specified module to the specified output stream. 4472 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out, 4473 bool ShouldPreserveUseListOrder, 4474 const ModuleSummaryIndex *Index, 4475 bool GenerateHash, ModuleHash *ModHash) { 4476 SmallVector<char, 0> Buffer; 4477 Buffer.reserve(256*1024); 4478 4479 // If this is darwin or another generic macho target, reserve space for the 4480 // header. 4481 Triple TT(M.getTargetTriple()); 4482 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 4483 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0); 4484 4485 BitcodeWriter Writer(Buffer); 4486 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash, 4487 ModHash); 4488 Writer.writeSymtab(); 4489 Writer.writeStrtab(); 4490 4491 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) 4492 emitDarwinBCHeaderAndTrailer(Buffer, TT); 4493 4494 // Write the generated bitstream to "Out". 4495 Out.write((char*)&Buffer.front(), Buffer.size()); 4496 } 4497 4498 void IndexBitcodeWriter::write() { 4499 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4500 4501 writeModuleVersion(); 4502 4503 // Write the module paths in the combined index. 4504 writeModStrings(); 4505 4506 // Write the summary combined index records. 4507 writeCombinedGlobalValueSummary(); 4508 4509 Stream.ExitBlock(); 4510 } 4511 4512 // Write the specified module summary index to the given raw output stream, 4513 // where it will be written in a new bitcode block. This is used when 4514 // writing the combined index file for ThinLTO. When writing a subset of the 4515 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map. 4516 void llvm::WriteIndexToFile( 4517 const ModuleSummaryIndex &Index, raw_ostream &Out, 4518 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) { 4519 SmallVector<char, 0> Buffer; 4520 Buffer.reserve(256 * 1024); 4521 4522 BitcodeWriter Writer(Buffer); 4523 Writer.writeIndex(&Index, ModuleToSummariesForIndex); 4524 Writer.writeStrtab(); 4525 4526 Out.write((char *)&Buffer.front(), Buffer.size()); 4527 } 4528 4529 namespace { 4530 4531 /// Class to manage the bitcode writing for a thin link bitcode file. 4532 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase { 4533 /// ModHash is for use in ThinLTO incremental build, generated while writing 4534 /// the module bitcode file. 4535 const ModuleHash *ModHash; 4536 4537 public: 4538 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder, 4539 BitstreamWriter &Stream, 4540 const ModuleSummaryIndex &Index, 4541 const ModuleHash &ModHash) 4542 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream, 4543 /*ShouldPreserveUseListOrder=*/false, &Index), 4544 ModHash(&ModHash) {} 4545 4546 void write(); 4547 4548 private: 4549 void writeSimplifiedModuleInfo(); 4550 }; 4551 4552 } // end anonymous namespace 4553 4554 // This function writes a simpilified module info for thin link bitcode file. 4555 // It only contains the source file name along with the name(the offset and 4556 // size in strtab) and linkage for global values. For the global value info 4557 // entry, in order to keep linkage at offset 5, there are three zeros used 4558 // as padding. 4559 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() { 4560 SmallVector<unsigned, 64> Vals; 4561 // Emit the module's source file name. 4562 { 4563 StringEncoding Bits = getStringEncoding(M.getSourceFileName()); 4564 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8); 4565 if (Bits == SE_Char6) 4566 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6); 4567 else if (Bits == SE_Fixed7) 4568 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7); 4569 4570 // MODULE_CODE_SOURCE_FILENAME: [namechar x N] 4571 auto Abbv = std::make_shared<BitCodeAbbrev>(); 4572 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME)); 4573 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 4574 Abbv->Add(AbbrevOpToUse); 4575 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv)); 4576 4577 for (const auto P : M.getSourceFileName()) 4578 Vals.push_back((unsigned char)P); 4579 4580 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev); 4581 Vals.clear(); 4582 } 4583 4584 // Emit the global variable information. 4585 for (const GlobalVariable &GV : M.globals()) { 4586 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage] 4587 Vals.push_back(StrtabBuilder.add(GV.getName())); 4588 Vals.push_back(GV.getName().size()); 4589 Vals.push_back(0); 4590 Vals.push_back(0); 4591 Vals.push_back(0); 4592 Vals.push_back(getEncodedLinkage(GV)); 4593 4594 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals); 4595 Vals.clear(); 4596 } 4597 4598 // Emit the function proto information. 4599 for (const Function &F : M) { 4600 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage] 4601 Vals.push_back(StrtabBuilder.add(F.getName())); 4602 Vals.push_back(F.getName().size()); 4603 Vals.push_back(0); 4604 Vals.push_back(0); 4605 Vals.push_back(0); 4606 Vals.push_back(getEncodedLinkage(F)); 4607 4608 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals); 4609 Vals.clear(); 4610 } 4611 4612 // Emit the alias information. 4613 for (const GlobalAlias &A : M.aliases()) { 4614 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage] 4615 Vals.push_back(StrtabBuilder.add(A.getName())); 4616 Vals.push_back(A.getName().size()); 4617 Vals.push_back(0); 4618 Vals.push_back(0); 4619 Vals.push_back(0); 4620 Vals.push_back(getEncodedLinkage(A)); 4621 4622 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals); 4623 Vals.clear(); 4624 } 4625 4626 // Emit the ifunc information. 4627 for (const GlobalIFunc &I : M.ifuncs()) { 4628 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage] 4629 Vals.push_back(StrtabBuilder.add(I.getName())); 4630 Vals.push_back(I.getName().size()); 4631 Vals.push_back(0); 4632 Vals.push_back(0); 4633 Vals.push_back(0); 4634 Vals.push_back(getEncodedLinkage(I)); 4635 4636 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals); 4637 Vals.clear(); 4638 } 4639 } 4640 4641 void ThinLinkBitcodeWriter::write() { 4642 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 4643 4644 writeModuleVersion(); 4645 4646 writeSimplifiedModuleInfo(); 4647 4648 writePerModuleGlobalValueSummary(); 4649 4650 // Write module hash. 4651 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash)); 4652 4653 Stream.ExitBlock(); 4654 } 4655 4656 void BitcodeWriter::writeThinLinkBitcode(const Module &M, 4657 const ModuleSummaryIndex &Index, 4658 const ModuleHash &ModHash) { 4659 assert(!WroteStrtab); 4660 4661 // The Mods vector is used by irsymtab::build, which requires non-const 4662 // Modules in case it needs to materialize metadata. But the bitcode writer 4663 // requires that the module is materialized, so we can cast to non-const here, 4664 // after checking that it is in fact materialized. 4665 assert(M.isMaterialized()); 4666 Mods.push_back(const_cast<Module *>(&M)); 4667 4668 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index, 4669 ModHash); 4670 ThinLinkWriter.write(); 4671 } 4672 4673 // Write the specified thin link bitcode file to the given raw output stream, 4674 // where it will be written in a new bitcode block. This is used when 4675 // writing the per-module index file for ThinLTO. 4676 void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, 4677 const ModuleSummaryIndex &Index, 4678 const ModuleHash &ModHash) { 4679 SmallVector<char, 0> Buffer; 4680 Buffer.reserve(256 * 1024); 4681 4682 BitcodeWriter Writer(Buffer); 4683 Writer.writeThinLinkBitcode(M, Index, ModHash); 4684 Writer.writeSymtab(); 4685 Writer.writeStrtab(); 4686 4687 Out.write((char *)&Buffer.front(), Buffer.size()); 4688 } 4689 4690 static const char *getSectionNameForBitcode(const Triple &T) { 4691 switch (T.getObjectFormat()) { 4692 case Triple::MachO: 4693 return "__LLVM,__bitcode"; 4694 case Triple::COFF: 4695 case Triple::ELF: 4696 case Triple::Wasm: 4697 case Triple::UnknownObjectFormat: 4698 return ".llvmbc"; 4699 case Triple::XCOFF: 4700 llvm_unreachable("XCOFF is not yet implemented"); 4701 break; 4702 } 4703 llvm_unreachable("Unimplemented ObjectFormatType"); 4704 } 4705 4706 static const char *getSectionNameForCommandline(const Triple &T) { 4707 switch (T.getObjectFormat()) { 4708 case Triple::MachO: 4709 return "__LLVM,__cmdline"; 4710 case Triple::COFF: 4711 case Triple::ELF: 4712 case Triple::Wasm: 4713 case Triple::UnknownObjectFormat: 4714 return ".llvmcmd"; 4715 case Triple::XCOFF: 4716 llvm_unreachable("XCOFF is not yet implemented"); 4717 break; 4718 } 4719 llvm_unreachable("Unimplemented ObjectFormatType"); 4720 } 4721 4722 void llvm::EmbedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf, 4723 bool EmbedBitcode, bool EmbedMarker, 4724 const std::vector<uint8_t> *CmdArgs) { 4725 // Save llvm.compiler.used and remove it. 4726 SmallVector<Constant *, 2> UsedArray; 4727 SmallPtrSet<GlobalValue *, 4> UsedGlobals; 4728 Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0); 4729 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true); 4730 for (auto *GV : UsedGlobals) { 4731 if (GV->getName() != "llvm.embedded.module" && 4732 GV->getName() != "llvm.cmdline") 4733 UsedArray.push_back( 4734 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4735 } 4736 if (Used) 4737 Used->eraseFromParent(); 4738 4739 // Embed the bitcode for the llvm module. 4740 std::string Data; 4741 ArrayRef<uint8_t> ModuleData; 4742 Triple T(M.getTargetTriple()); 4743 // Create a constant that contains the bitcode. 4744 // In case of embedding a marker, ignore the input Buf and use the empty 4745 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty. 4746 if (EmbedBitcode) { 4747 if (!isBitcode((const unsigned char *)Buf.getBufferStart(), 4748 (const unsigned char *)Buf.getBufferEnd())) { 4749 // If the input is LLVM Assembly, bitcode is produced by serializing 4750 // the module. Use-lists order need to be preserved in this case. 4751 llvm::raw_string_ostream OS(Data); 4752 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 4753 ModuleData = 4754 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 4755 } else 4756 // If the input is LLVM bitcode, write the input byte stream directly. 4757 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 4758 Buf.getBufferSize()); 4759 } 4760 llvm::Constant *ModuleConstant = 4761 llvm::ConstantDataArray::get(M.getContext(), ModuleData); 4762 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 4763 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 4764 ModuleConstant); 4765 GV->setSection(getSectionNameForBitcode(T)); 4766 UsedArray.push_back( 4767 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4768 if (llvm::GlobalVariable *Old = 4769 M.getGlobalVariable("llvm.embedded.module", true)) { 4770 assert(Old->hasOneUse() && 4771 "llvm.embedded.module can only be used once in llvm.compiler.used"); 4772 GV->takeName(Old); 4773 Old->eraseFromParent(); 4774 } else { 4775 GV->setName("llvm.embedded.module"); 4776 } 4777 4778 // Skip if only bitcode needs to be embedded. 4779 if (EmbedMarker) { 4780 // Embed command-line options. 4781 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs->data()), 4782 CmdArgs->size()); 4783 llvm::Constant *CmdConstant = 4784 llvm::ConstantDataArray::get(M.getContext(), CmdData); 4785 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true, 4786 llvm::GlobalValue::PrivateLinkage, 4787 CmdConstant); 4788 GV->setSection(getSectionNameForCommandline(T)); 4789 UsedArray.push_back( 4790 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 4791 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) { 4792 assert(Old->hasOneUse() && 4793 "llvm.cmdline can only be used once in llvm.compiler.used"); 4794 GV->takeName(Old); 4795 Old->eraseFromParent(); 4796 } else { 4797 GV->setName("llvm.cmdline"); 4798 } 4799 } 4800 4801 if (UsedArray.empty()) 4802 return; 4803 4804 // Recreate llvm.compiler.used. 4805 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 4806 auto *NewUsed = new GlobalVariable( 4807 M, ATy, false, llvm::GlobalValue::AppendingLinkage, 4808 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 4809 NewUsed->setSection("llvm.metadata"); 4810 } 4811