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