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