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