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