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