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