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