LLVM 19.0.0git
BitcodeWriter.cpp
Go to the documentation of this file.
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
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/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/StringRef.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
34#include "llvm/IR/Comdat.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
38#include "llvm/IR/DebugLoc.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalIFunc.h"
44#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Module.h"
54#include "llvm/IR/Operator.h"
55#include "llvm/IR/Type.h"
57#include "llvm/IR/Value.h"
65#include "llvm/Support/Endian.h"
66#include "llvm/Support/Error.h"
69#include "llvm/Support/SHA1.h"
72#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
77#include <map>
78#include <memory>
79#include <optional>
80#include <string>
81#include <utility>
82#include <vector>
83
84using namespace llvm;
85
87 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
88 cl::desc("Number of metadatas above which we emit an index "
89 "to enable lazy-loading"));
91 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
92 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
93
95 "write-relbf-to-summary", cl::Hidden, cl::init(false),
96 cl::desc("Write relative block frequency to function summary "));
97
98namespace llvm {
100}
101
102namespace {
103
104/// These are manifest constants used by the bitcode writer. They do not need to
105/// be kept in sync with the reader, but need to be consistent within this file.
106enum {
107 // VALUE_SYMTAB_BLOCK abbrev id's.
108 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
109 VST_ENTRY_7_ABBREV,
110 VST_ENTRY_6_ABBREV,
111 VST_BBENTRY_6_ABBREV,
112
113 // CONSTANTS_BLOCK abbrev id's.
114 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
115 CONSTANTS_INTEGER_ABBREV,
116 CONSTANTS_CE_CAST_Abbrev,
117 CONSTANTS_NULL_Abbrev,
118
119 // FUNCTION_BLOCK abbrev id's.
120 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
121 FUNCTION_INST_UNOP_ABBREV,
122 FUNCTION_INST_UNOP_FLAGS_ABBREV,
123 FUNCTION_INST_BINOP_ABBREV,
124 FUNCTION_INST_BINOP_FLAGS_ABBREV,
125 FUNCTION_INST_CAST_ABBREV,
126 FUNCTION_INST_CAST_FLAGS_ABBREV,
127 FUNCTION_INST_RET_VOID_ABBREV,
128 FUNCTION_INST_RET_VAL_ABBREV,
129 FUNCTION_INST_UNREACHABLE_ABBREV,
130 FUNCTION_INST_GEP_ABBREV,
131};
132
133/// Abstract class to manage the bitcode writing, subclassed for each bitcode
134/// file type.
135class BitcodeWriterBase {
136protected:
137 /// The stream created and owned by the client.
138 BitstreamWriter &Stream;
139
140 StringTableBuilder &StrtabBuilder;
141
142public:
143 /// Constructs a BitcodeWriterBase object that writes to the provided
144 /// \p Stream.
145 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
146 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
147
148protected:
149 void writeModuleVersion();
150};
151
152void BitcodeWriterBase::writeModuleVersion() {
153 // VERSION: [version#]
154 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
155}
156
157/// Base class to manage the module bitcode writing, currently subclassed for
158/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
159class ModuleBitcodeWriterBase : public BitcodeWriterBase {
160protected:
161 /// The Module to write to bitcode.
162 const Module &M;
163
164 /// Enumerates ids for all values in the module.
166
167 /// Optional per-module index to write for ThinLTO.
169
170 /// Map that holds the correspondence between GUIDs in the summary index,
171 /// that came from indirect call profiles, and a value id generated by this
172 /// class to use in the VST and summary block records.
173 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
174
175 /// Tracks the last value id recorded in the GUIDToValueMap.
176 unsigned GlobalValueId;
177
178 /// Saves the offset of the VSTOffset record that must eventually be
179 /// backpatched with the offset of the actual VST.
180 uint64_t VSTOffsetPlaceholder = 0;
181
182public:
183 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
184 /// writing to the provided \p Buffer.
185 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
186 BitstreamWriter &Stream,
187 bool ShouldPreserveUseListOrder,
189 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
190 VE(M, ShouldPreserveUseListOrder), Index(Index) {
191 // Assign ValueIds to any callee values in the index that came from
192 // indirect call profiles and were recorded as a GUID not a Value*
193 // (which would have been assigned an ID by the ValueEnumerator).
194 // The starting ValueId is just after the number of values in the
195 // ValueEnumerator, so that they can be emitted in the VST.
196 GlobalValueId = VE.getValues().size();
197 if (!Index)
198 return;
199 for (const auto &GUIDSummaryLists : *Index)
200 // Examine all summaries for this GUID.
201 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
202 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
203 // For each call in the function summary, see if the call
204 // is to a GUID (which means it is for an indirect call,
205 // otherwise we would have a Value for it). If so, synthesize
206 // a value id.
207 for (auto &CallEdge : FS->calls())
208 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
209 assignValueId(CallEdge.first.getGUID());
210 }
211
212protected:
213 void writePerModuleGlobalValueSummary();
214
215private:
216 void writePerModuleFunctionSummaryRecord(
218 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
219 unsigned CallsiteAbbrev, unsigned AllocAbbrev, const Function &F);
220 void writeModuleLevelReferences(const GlobalVariable &V,
222 unsigned FSModRefsAbbrev,
223 unsigned FSModVTableRefsAbbrev);
224
225 void assignValueId(GlobalValue::GUID ValGUID) {
226 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
227 }
228
229 unsigned getValueId(GlobalValue::GUID ValGUID) {
230 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
231 // Expect that any GUID value had a value Id assigned by an
232 // earlier call to assignValueId.
233 assert(VMI != GUIDToValueIdMap.end() &&
234 "GUID does not have assigned value Id");
235 return VMI->second;
236 }
237
238 // Helper to get the valueId for the type of value recorded in VI.
239 unsigned getValueId(ValueInfo VI) {
240 if (!VI.haveGVs() || !VI.getValue())
241 return getValueId(VI.getGUID());
242 return VE.getValueID(VI.getValue());
243 }
244
245 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
246};
247
248/// Class to manage the bitcode writing for a module.
249class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
250 /// Pointer to the buffer allocated by caller for bitcode writing.
251 const SmallVectorImpl<char> &Buffer;
252
253 /// True if a module hash record should be written.
254 bool GenerateHash;
255
256 /// If non-null, when GenerateHash is true, the resulting hash is written
257 /// into ModHash.
258 ModuleHash *ModHash;
259
260 SHA1 Hasher;
261
262 /// The start bit of the identification block.
263 uint64_t BitcodeStartBit;
264
265public:
266 /// Constructs a ModuleBitcodeWriter object for the given Module,
267 /// writing to the provided \p Buffer.
268 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
269 StringTableBuilder &StrtabBuilder,
270 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
271 const ModuleSummaryIndex *Index, bool GenerateHash,
272 ModuleHash *ModHash = nullptr)
273 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
274 ShouldPreserveUseListOrder, Index),
275 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
276 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
277
278 /// Emit the current module to the bitstream.
279 void write();
280
281private:
282 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
283
284 size_t addToStrtab(StringRef Str);
285
286 void writeAttributeGroupTable();
287 void writeAttributeTable();
288 void writeTypeTable();
289 void writeComdats();
290 void writeValueSymbolTableForwardDecl();
291 void writeModuleInfo();
292 void writeValueAsMetadata(const ValueAsMetadata *MD,
295 unsigned Abbrev);
296 unsigned createDILocationAbbrev();
298 unsigned &Abbrev);
299 unsigned createGenericDINodeAbbrev();
301 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
303 unsigned Abbrev);
306 unsigned Abbrev);
307 void writeDIEnumerator(const DIEnumerator *N,
308 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
310 unsigned Abbrev);
311 void writeDIStringType(const DIStringType *N,
312 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
314 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
319 unsigned Abbrev);
321 unsigned Abbrev);
323 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
324 void writeDISubprogram(const DISubprogram *N,
325 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
327 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
330 unsigned Abbrev);
332 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
334 unsigned Abbrev);
336 unsigned Abbrev);
338 unsigned Abbrev);
341 unsigned Abbrev);
343 unsigned Abbrev);
346 unsigned Abbrev);
349 unsigned Abbrev);
352 unsigned Abbrev);
354 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
355 void writeDILabel(const DILabel *N,
356 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
357 void writeDIExpression(const DIExpression *N,
358 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
361 unsigned Abbrev);
363 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
366 unsigned Abbrev);
367 unsigned createNamedMetadataAbbrev();
368 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
369 unsigned createMetadataStringsAbbrev();
370 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
372 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
374 std::vector<unsigned> *MDAbbrevs = nullptr,
375 std::vector<uint64_t> *IndexPos = nullptr);
376 void writeModuleMetadata();
377 void writeFunctionMetadata(const Function &F);
378 void writeFunctionMetadataAttachment(const Function &F);
379 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
380 const GlobalObject &GO);
381 void writeModuleMetadataKinds();
382 void writeOperandBundleTags();
383 void writeSyncScopeNames();
384 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
385 void writeModuleConstants();
386 bool pushValueAndType(const Value *V, unsigned InstID,
388 void writeOperandBundles(const CallBase &CB, unsigned InstID);
389 void pushValue(const Value *V, unsigned InstID,
391 void pushValueSigned(const Value *V, unsigned InstID,
393 void writeInstruction(const Instruction &I, unsigned InstID,
395 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
396 void writeGlobalValueSymbolTable(
397 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
398 void writeUseList(UseListOrder &&Order);
399 void writeUseListBlock(const Function *F);
400 void
401 writeFunction(const Function &F,
402 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
403 void writeBlockInfo();
404 void writeModuleHash(size_t BlockStartPos);
405
406 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
407 return unsigned(SSID);
408 }
409
410 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
411};
412
413/// Class to manage the bitcode writing for a combined index.
414class IndexBitcodeWriter : public BitcodeWriterBase {
415 /// The combined index to write to bitcode.
417
418 /// When writing a subset of the index for distributed backends, client
419 /// provides a map of modules to the corresponding GUIDs/summaries to write.
420 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
421
422 /// Map that holds the correspondence between the GUID used in the combined
423 /// index and a value id generated by this class to use in references.
424 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
425
426 // The sorted stack id indices actually used in the summary entries being
427 // written, which will be a subset of those in the full index in the case of
428 // distributed indexes.
429 std::vector<unsigned> StackIdIndices;
430
431 /// Tracks the last value id recorded in the GUIDToValueMap.
432 unsigned GlobalValueId = 0;
433
434 /// Tracks the assignment of module paths in the module path string table to
435 /// an id assigned for use in summary references to the module path.
437
438public:
439 /// Constructs a IndexBitcodeWriter object for the given combined index,
440 /// writing to the provided \p Buffer. When writing a subset of the index
441 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
442 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
444 const std::map<std::string, GVSummaryMapTy>
445 *ModuleToSummariesForIndex = nullptr)
446 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
447 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
448 // Assign unique value ids to all summaries to be written, for use
449 // in writing out the call graph edges. Save the mapping from GUID
450 // to the new global value id to use when writing those edges, which
451 // are currently saved in the index in terms of GUID.
452 forEachSummary([&](GVInfo I, bool IsAliasee) {
453 GUIDToValueIdMap[I.first] = ++GlobalValueId;
454 if (IsAliasee)
455 return;
456 auto *FS = dyn_cast<FunctionSummary>(I.second);
457 if (!FS)
458 return;
459 // Record all stack id indices actually used in the summary entries being
460 // written, so that we can compact them in the case of distributed ThinLTO
461 // indexes.
462 for (auto &CI : FS->callsites()) {
463 // If the stack id list is empty, this callsite info was synthesized for
464 // a missing tail call frame. Ensure that the callee's GUID gets a value
465 // id. Normally we only generate these for defined summaries, which in
466 // the case of distributed ThinLTO is only the functions already defined
467 // in the module or that we want to import. We don't bother to include
468 // all the callee symbols as they aren't normally needed in the backend.
469 // However, for the synthesized callsite infos we do need the callee
470 // GUID in the backend so that we can correlate the identified callee
471 // with this callsite info (which for non-tail calls is done by the
472 // ordering of the callsite infos and verified via stack ids).
473 if (CI.StackIdIndices.empty()) {
474 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
475 continue;
476 }
477 for (auto Idx : CI.StackIdIndices)
478 StackIdIndices.push_back(Idx);
479 }
480 for (auto &AI : FS->allocs())
481 for (auto &MIB : AI.MIBs)
482 for (auto Idx : MIB.StackIdIndices)
483 StackIdIndices.push_back(Idx);
484 });
485 llvm::sort(StackIdIndices);
486 StackIdIndices.erase(
487 std::unique(StackIdIndices.begin(), StackIdIndices.end()),
488 StackIdIndices.end());
489 }
490
491 /// The below iterator returns the GUID and associated summary.
492 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
493
494 /// Calls the callback for each value GUID and summary to be written to
495 /// bitcode. This hides the details of whether they are being pulled from the
496 /// entire index or just those in a provided ModuleToSummariesForIndex map.
497 template<typename Functor>
498 void forEachSummary(Functor Callback) {
499 if (ModuleToSummariesForIndex) {
500 for (auto &M : *ModuleToSummariesForIndex)
501 for (auto &Summary : M.second) {
502 Callback(Summary, false);
503 // Ensure aliasee is handled, e.g. for assigning a valueId,
504 // even if we are not importing the aliasee directly (the
505 // imported alias will contain a copy of aliasee).
506 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
507 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
508 }
509 } else {
510 for (auto &Summaries : Index)
511 for (auto &Summary : Summaries.second.SummaryList)
512 Callback({Summaries.first, Summary.get()}, false);
513 }
514 }
515
516 /// Calls the callback for each entry in the modulePaths StringMap that
517 /// should be written to the module path string table. This hides the details
518 /// of whether they are being pulled from the entire index or just those in a
519 /// provided ModuleToSummariesForIndex map.
520 template <typename Functor> void forEachModule(Functor Callback) {
521 if (ModuleToSummariesForIndex) {
522 for (const auto &M : *ModuleToSummariesForIndex) {
523 const auto &MPI = Index.modulePaths().find(M.first);
524 if (MPI == Index.modulePaths().end()) {
525 // This should only happen if the bitcode file was empty, in which
526 // case we shouldn't be importing (the ModuleToSummariesForIndex
527 // would only include the module we are writing and index for).
528 assert(ModuleToSummariesForIndex->size() == 1);
529 continue;
530 }
531 Callback(*MPI);
532 }
533 } else {
534 // Since StringMap iteration order isn't guaranteed, order by path string
535 // first.
536 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
537 // map lookup.
538 std::vector<StringRef> ModulePaths;
539 for (auto &[ModPath, _] : Index.modulePaths())
540 ModulePaths.push_back(ModPath);
541 llvm::sort(ModulePaths.begin(), ModulePaths.end());
542 for (auto &ModPath : ModulePaths)
543 Callback(*Index.modulePaths().find(ModPath));
544 }
545 }
546
547 /// Main entry point for writing a combined index to bitcode.
548 void write();
549
550private:
551 void writeModStrings();
552 void writeCombinedGlobalValueSummary();
553
554 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
555 auto VMI = GUIDToValueIdMap.find(ValGUID);
556 if (VMI == GUIDToValueIdMap.end())
557 return std::nullopt;
558 return VMI->second;
559 }
560
561 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
562};
563
564} // end anonymous namespace
565
566static unsigned getEncodedCastOpcode(unsigned Opcode) {
567 switch (Opcode) {
568 default: llvm_unreachable("Unknown cast instruction!");
569 case Instruction::Trunc : return bitc::CAST_TRUNC;
570 case Instruction::ZExt : return bitc::CAST_ZEXT;
571 case Instruction::SExt : return bitc::CAST_SEXT;
572 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
573 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
574 case Instruction::UIToFP : return bitc::CAST_UITOFP;
575 case Instruction::SIToFP : return bitc::CAST_SITOFP;
576 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
577 case Instruction::FPExt : return bitc::CAST_FPEXT;
578 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
579 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
580 case Instruction::BitCast : return bitc::CAST_BITCAST;
581 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
582 }
583}
584
585static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
586 switch (Opcode) {
587 default: llvm_unreachable("Unknown binary instruction!");
588 case Instruction::FNeg: return bitc::UNOP_FNEG;
589 }
590}
591
592static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
593 switch (Opcode) {
594 default: llvm_unreachable("Unknown binary instruction!");
595 case Instruction::Add:
596 case Instruction::FAdd: return bitc::BINOP_ADD;
597 case Instruction::Sub:
598 case Instruction::FSub: return bitc::BINOP_SUB;
599 case Instruction::Mul:
600 case Instruction::FMul: return bitc::BINOP_MUL;
601 case Instruction::UDiv: return bitc::BINOP_UDIV;
602 case Instruction::FDiv:
603 case Instruction::SDiv: return bitc::BINOP_SDIV;
604 case Instruction::URem: return bitc::BINOP_UREM;
605 case Instruction::FRem:
606 case Instruction::SRem: return bitc::BINOP_SREM;
607 case Instruction::Shl: return bitc::BINOP_SHL;
608 case Instruction::LShr: return bitc::BINOP_LSHR;
609 case Instruction::AShr: return bitc::BINOP_ASHR;
610 case Instruction::And: return bitc::BINOP_AND;
611 case Instruction::Or: return bitc::BINOP_OR;
612 case Instruction::Xor: return bitc::BINOP_XOR;
613 }
614}
615
617 switch (Op) {
618 default: llvm_unreachable("Unknown RMW operation!");
624 case AtomicRMWInst::Or: return bitc::RMW_OR;
635 return bitc::RMW_UINC_WRAP;
637 return bitc::RMW_UDEC_WRAP;
638 }
639}
640
641static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
642 switch (Ordering) {
643 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
644 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
645 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
646 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
647 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
648 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
649 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
650 }
651 llvm_unreachable("Invalid ordering");
652}
653
654static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
655 StringRef Str, unsigned AbbrevToUse) {
657
658 // Code: [strchar x N]
659 for (char C : Str) {
660 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
661 AbbrevToUse = 0;
662 Vals.push_back(C);
663 }
664
665 // Emit the finished record.
666 Stream.EmitRecord(Code, Vals, AbbrevToUse);
667}
668
670 switch (Kind) {
671 case Attribute::Alignment:
673 case Attribute::AllocAlign:
675 case Attribute::AllocSize:
677 case Attribute::AlwaysInline:
679 case Attribute::Builtin:
681 case Attribute::ByVal:
683 case Attribute::Convergent:
685 case Attribute::InAlloca:
687 case Attribute::Cold:
689 case Attribute::DisableSanitizerInstrumentation:
691 case Attribute::FnRetThunkExtern:
693 case Attribute::Hot:
694 return bitc::ATTR_KIND_HOT;
695 case Attribute::ElementType:
697 case Attribute::InlineHint:
699 case Attribute::InReg:
701 case Attribute::JumpTable:
703 case Attribute::MinSize:
705 case Attribute::AllocatedPointer:
707 case Attribute::AllocKind:
709 case Attribute::Memory:
711 case Attribute::NoFPClass:
713 case Attribute::Naked:
715 case Attribute::Nest:
717 case Attribute::NoAlias:
719 case Attribute::NoBuiltin:
721 case Attribute::NoCallback:
723 case Attribute::NoCapture:
725 case Attribute::NoDuplicate:
727 case Attribute::NoFree:
729 case Attribute::NoImplicitFloat:
731 case Attribute::NoInline:
733 case Attribute::NoRecurse:
735 case Attribute::NoMerge:
737 case Attribute::NonLazyBind:
739 case Attribute::NonNull:
741 case Attribute::Dereferenceable:
743 case Attribute::DereferenceableOrNull:
745 case Attribute::NoRedZone:
747 case Attribute::NoReturn:
749 case Attribute::NoSync:
751 case Attribute::NoCfCheck:
753 case Attribute::NoProfile:
755 case Attribute::SkipProfile:
757 case Attribute::NoUnwind:
759 case Attribute::NoSanitizeBounds:
761 case Attribute::NoSanitizeCoverage:
763 case Attribute::NullPointerIsValid:
765 case Attribute::OptimizeForDebugging:
767 case Attribute::OptForFuzzing:
769 case Attribute::OptimizeForSize:
771 case Attribute::OptimizeNone:
773 case Attribute::ReadNone:
775 case Attribute::ReadOnly:
777 case Attribute::Returned:
779 case Attribute::ReturnsTwice:
781 case Attribute::SExt:
783 case Attribute::Speculatable:
785 case Attribute::StackAlignment:
787 case Attribute::StackProtect:
789 case Attribute::StackProtectReq:
791 case Attribute::StackProtectStrong:
793 case Attribute::SafeStack:
795 case Attribute::ShadowCallStack:
797 case Attribute::StrictFP:
799 case Attribute::StructRet:
801 case Attribute::SanitizeAddress:
803 case Attribute::SanitizeHWAddress:
805 case Attribute::SanitizeThread:
807 case Attribute::SanitizeMemory:
809 case Attribute::SpeculativeLoadHardening:
811 case Attribute::SwiftError:
813 case Attribute::SwiftSelf:
815 case Attribute::SwiftAsync:
817 case Attribute::UWTable:
819 case Attribute::VScaleRange:
821 case Attribute::WillReturn:
823 case Attribute::WriteOnly:
825 case Attribute::ZExt:
827 case Attribute::ImmArg:
829 case Attribute::SanitizeMemTag:
831 case Attribute::Preallocated:
833 case Attribute::NoUndef:
835 case Attribute::ByRef:
837 case Attribute::MustProgress:
839 case Attribute::PresplitCoroutine:
841 case Attribute::Writable:
843 case Attribute::CoroDestroyOnlyWhenComplete:
845 case Attribute::DeadOnUnwind:
848 llvm_unreachable("Can not encode end-attribute kinds marker.");
849 case Attribute::None:
850 llvm_unreachable("Can not encode none-attribute.");
853 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
854 }
855
856 llvm_unreachable("Trying to encode unknown attribute");
857}
858
859void ModuleBitcodeWriter::writeAttributeGroupTable() {
860 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
862 if (AttrGrps.empty()) return;
863
865
867 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
868 unsigned AttrListIndex = Pair.first;
869 AttributeSet AS = Pair.second;
870 Record.push_back(VE.getAttributeGroupID(Pair));
871 Record.push_back(AttrListIndex);
872
873 for (Attribute Attr : AS) {
874 if (Attr.isEnumAttribute()) {
875 Record.push_back(0);
876 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
877 } else if (Attr.isIntAttribute()) {
878 Record.push_back(1);
879 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
880 Record.push_back(Attr.getValueAsInt());
881 } else if (Attr.isStringAttribute()) {
882 StringRef Kind = Attr.getKindAsString();
883 StringRef Val = Attr.getValueAsString();
884
885 Record.push_back(Val.empty() ? 3 : 4);
886 Record.append(Kind.begin(), Kind.end());
887 Record.push_back(0);
888 if (!Val.empty()) {
889 Record.append(Val.begin(), Val.end());
890 Record.push_back(0);
891 }
892 } else {
893 assert(Attr.isTypeAttribute());
894 Type *Ty = Attr.getValueAsType();
895 Record.push_back(Ty ? 6 : 5);
896 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
897 if (Ty)
898 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
899 }
900 }
901
903 Record.clear();
904 }
905
906 Stream.ExitBlock();
907}
908
909void ModuleBitcodeWriter::writeAttributeTable() {
910 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
911 if (Attrs.empty()) return;
912
914
916 for (const AttributeList &AL : Attrs) {
917 for (unsigned i : AL.indexes()) {
918 AttributeSet AS = AL.getAttributes(i);
919 if (AS.hasAttributes())
920 Record.push_back(VE.getAttributeGroupID({i, AS}));
921 }
922
924 Record.clear();
925 }
926
927 Stream.ExitBlock();
928}
929
930/// WriteTypeTable - Write out the type table for a module.
931void ModuleBitcodeWriter::writeTypeTable() {
932 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
933
934 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
936
938
939 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
940 auto Abbv = std::make_shared<BitCodeAbbrev>();
942 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
943 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
944
945 // Abbrev for TYPE_CODE_FUNCTION.
946 Abbv = std::make_shared<BitCodeAbbrev>();
948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
950 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
951 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
952
953 // Abbrev for TYPE_CODE_STRUCT_ANON.
954 Abbv = std::make_shared<BitCodeAbbrev>();
956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
959 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
960
961 // Abbrev for TYPE_CODE_STRUCT_NAME.
962 Abbv = std::make_shared<BitCodeAbbrev>();
966 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
967
968 // Abbrev for TYPE_CODE_STRUCT_NAMED.
969 Abbv = std::make_shared<BitCodeAbbrev>();
971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
974 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
975
976 // Abbrev for TYPE_CODE_ARRAY.
977 Abbv = std::make_shared<BitCodeAbbrev>();
979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
981 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
982
983 // Emit an entry count so the reader can reserve space.
984 TypeVals.push_back(TypeList.size());
985 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
986 TypeVals.clear();
987
988 // Loop over all of the types, emitting each in turn.
989 for (Type *T : TypeList) {
990 int AbbrevToUse = 0;
991 unsigned Code = 0;
992
993 switch (T->getTypeID()) {
1007 case Type::IntegerTyID:
1008 // INTEGER: [width]
1010 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1011 break;
1012 case Type::PointerTyID: {
1013 PointerType *PTy = cast<PointerType>(T);
1014 unsigned AddressSpace = PTy->getAddressSpace();
1015 // OPAQUE_POINTER: [address space]
1017 TypeVals.push_back(AddressSpace);
1018 if (AddressSpace == 0)
1019 AbbrevToUse = OpaquePtrAbbrev;
1020 break;
1021 }
1022 case Type::FunctionTyID: {
1023 FunctionType *FT = cast<FunctionType>(T);
1024 // FUNCTION: [isvararg, retty, paramty x N]
1026 TypeVals.push_back(FT->isVarArg());
1027 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1028 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1029 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1030 AbbrevToUse = FunctionAbbrev;
1031 break;
1032 }
1033 case Type::StructTyID: {
1034 StructType *ST = cast<StructType>(T);
1035 // STRUCT: [ispacked, eltty x N]
1036 TypeVals.push_back(ST->isPacked());
1037 // Output all of the element types.
1038 for (Type *ET : ST->elements())
1039 TypeVals.push_back(VE.getTypeID(ET));
1040
1041 if (ST->isLiteral()) {
1043 AbbrevToUse = StructAnonAbbrev;
1044 } else {
1045 if (ST->isOpaque()) {
1047 } else {
1049 AbbrevToUse = StructNamedAbbrev;
1050 }
1051
1052 // Emit the name if it is present.
1053 if (!ST->getName().empty())
1055 StructNameAbbrev);
1056 }
1057 break;
1058 }
1059 case Type::ArrayTyID: {
1060 ArrayType *AT = cast<ArrayType>(T);
1061 // ARRAY: [numelts, eltty]
1063 TypeVals.push_back(AT->getNumElements());
1064 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1065 AbbrevToUse = ArrayAbbrev;
1066 break;
1067 }
1070 VectorType *VT = cast<VectorType>(T);
1071 // VECTOR [numelts, eltty] or
1072 // [numelts, eltty, scalable]
1074 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1075 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1076 if (isa<ScalableVectorType>(VT))
1077 TypeVals.push_back(true);
1078 break;
1079 }
1080 case Type::TargetExtTyID: {
1081 TargetExtType *TET = cast<TargetExtType>(T);
1084 StructNameAbbrev);
1085 TypeVals.push_back(TET->getNumTypeParameters());
1086 for (Type *InnerTy : TET->type_params())
1087 TypeVals.push_back(VE.getTypeID(InnerTy));
1088 for (unsigned IntParam : TET->int_params())
1089 TypeVals.push_back(IntParam);
1090 break;
1091 }
1093 llvm_unreachable("Typed pointers cannot be added to IR modules");
1094 }
1095
1096 // Emit the finished record.
1097 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1098 TypeVals.clear();
1099 }
1100
1101 Stream.ExitBlock();
1102}
1103
1104static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1105 switch (Linkage) {
1107 return 0;
1109 return 16;
1111 return 2;
1113 return 3;
1115 return 18;
1117 return 7;
1119 return 8;
1121 return 9;
1123 return 17;
1125 return 19;
1127 return 12;
1128 }
1129 llvm_unreachable("Invalid linkage");
1130}
1131
1132static unsigned getEncodedLinkage(const GlobalValue &GV) {
1133 return getEncodedLinkage(GV.getLinkage());
1134}
1135
1137 uint64_t RawFlags = 0;
1138 RawFlags |= Flags.ReadNone;
1139 RawFlags |= (Flags.ReadOnly << 1);
1140 RawFlags |= (Flags.NoRecurse << 2);
1141 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1142 RawFlags |= (Flags.NoInline << 4);
1143 RawFlags |= (Flags.AlwaysInline << 5);
1144 RawFlags |= (Flags.NoUnwind << 6);
1145 RawFlags |= (Flags.MayThrow << 7);
1146 RawFlags |= (Flags.HasUnknownCall << 8);
1147 RawFlags |= (Flags.MustBeUnreachable << 9);
1148 return RawFlags;
1149}
1150
1151// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1152// in BitcodeReader.cpp.
1154 uint64_t RawFlags = 0;
1155
1156 RawFlags |= Flags.NotEligibleToImport; // bool
1157 RawFlags |= (Flags.Live << 1);
1158 RawFlags |= (Flags.DSOLocal << 2);
1159 RawFlags |= (Flags.CanAutoHide << 3);
1160
1161 // Linkage don't need to be remapped at that time for the summary. Any future
1162 // change to the getEncodedLinkage() function will need to be taken into
1163 // account here as well.
1164 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1165
1166 RawFlags |= (Flags.Visibility << 8); // 2 bits
1167
1168 return RawFlags;
1169}
1170
1172 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1173 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1174 return RawFlags;
1175}
1176
1178 uint64_t RawFlags = 0;
1179
1180 RawFlags |= CI.Hotness; // 3 bits
1181 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1182
1183 return RawFlags;
1184}
1185
1187 uint64_t RawFlags = 0;
1188
1189 RawFlags |= CI.RelBlockFreq; // CalleeInfo::RelBlockFreqBits bits
1190 RawFlags |= (CI.HasTailCall << CalleeInfo::RelBlockFreqBits); // 1 bit
1191
1192 return RawFlags;
1193}
1194
1195static unsigned getEncodedVisibility(const GlobalValue &GV) {
1196 switch (GV.getVisibility()) {
1197 case GlobalValue::DefaultVisibility: return 0;
1198 case GlobalValue::HiddenVisibility: return 1;
1199 case GlobalValue::ProtectedVisibility: return 2;
1200 }
1201 llvm_unreachable("Invalid visibility");
1202}
1203
1204static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1205 switch (GV.getDLLStorageClass()) {
1206 case GlobalValue::DefaultStorageClass: return 0;
1209 }
1210 llvm_unreachable("Invalid DLL storage class");
1211}
1212
1213static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1214 switch (GV.getThreadLocalMode()) {
1215 case GlobalVariable::NotThreadLocal: return 0;
1216 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1217 case GlobalVariable::LocalDynamicTLSModel: return 2;
1218 case GlobalVariable::InitialExecTLSModel: return 3;
1219 case GlobalVariable::LocalExecTLSModel: return 4;
1220 }
1221 llvm_unreachable("Invalid TLS model");
1222}
1223
1224static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1225 switch (C.getSelectionKind()) {
1226 case Comdat::Any:
1228 case Comdat::ExactMatch:
1230 case Comdat::Largest:
1234 case Comdat::SameSize:
1236 }
1237 llvm_unreachable("Invalid selection kind");
1238}
1239
1240static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1241 switch (GV.getUnnamedAddr()) {
1242 case GlobalValue::UnnamedAddr::None: return 0;
1243 case GlobalValue::UnnamedAddr::Local: return 2;
1244 case GlobalValue::UnnamedAddr::Global: return 1;
1245 }
1246 llvm_unreachable("Invalid unnamed_addr");
1247}
1248
1249size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1250 if (GenerateHash)
1251 Hasher.update(Str);
1252 return StrtabBuilder.add(Str);
1253}
1254
1255void ModuleBitcodeWriter::writeComdats() {
1257 for (const Comdat *C : VE.getComdats()) {
1258 // COMDAT: [strtab offset, strtab size, selection_kind]
1259 Vals.push_back(addToStrtab(C->getName()));
1260 Vals.push_back(C->getName().size());
1262 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1263 Vals.clear();
1264 }
1265}
1266
1267/// Write a record that will eventually hold the word offset of the
1268/// module-level VST. For now the offset is 0, which will be backpatched
1269/// after the real VST is written. Saves the bit offset to backpatch.
1270void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1271 // Write a placeholder value in for the offset of the real VST,
1272 // which is written after the function blocks so that it can include
1273 // the offset of each function. The placeholder offset will be
1274 // updated when the real VST is written.
1275 auto Abbv = std::make_shared<BitCodeAbbrev>();
1277 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1278 // hold the real VST offset. Must use fixed instead of VBR as we don't
1279 // know how many VBR chunks to reserve ahead of time.
1281 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1282
1283 // Emit the placeholder
1285 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1286
1287 // Compute and save the bit offset to the placeholder, which will be
1288 // patched when the real VST is written. We can simply subtract the 32-bit
1289 // fixed size from the current bit number to get the location to backpatch.
1290 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1291}
1292
1294
1295/// Determine the encoding to use for the given string name and length.
1297 bool isChar6 = true;
1298 for (char C : Str) {
1299 if (isChar6)
1300 isChar6 = BitCodeAbbrevOp::isChar6(C);
1301 if ((unsigned char)C & 128)
1302 // don't bother scanning the rest.
1303 return SE_Fixed8;
1304 }
1305 if (isChar6)
1306 return SE_Char6;
1307 return SE_Fixed7;
1308}
1309
1310static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1311 "Sanitizer Metadata is too large for naive serialization.");
1312static unsigned
1314 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1315 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1316}
1317
1318/// Emit top-level description of module, including target triple, inline asm,
1319/// descriptors for global variables, and function prototype info.
1320/// Returns the bit offset to backpatch with the location of the real VST.
1321void ModuleBitcodeWriter::writeModuleInfo() {
1322 // Emit various pieces of data attached to a module.
1323 if (!M.getTargetTriple().empty())
1324 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1325 0 /*TODO*/);
1326 const std::string &DL = M.getDataLayoutStr();
1327 if (!DL.empty())
1329 if (!M.getModuleInlineAsm().empty())
1330 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1331 0 /*TODO*/);
1332
1333 // Emit information about sections and GC, computing how many there are. Also
1334 // compute the maximum alignment value.
1335 std::map<std::string, unsigned> SectionMap;
1336 std::map<std::string, unsigned> GCMap;
1337 MaybeAlign MaxAlignment;
1338 unsigned MaxGlobalType = 0;
1339 const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1340 if (A)
1341 MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1342 };
1343 for (const GlobalVariable &GV : M.globals()) {
1344 UpdateMaxAlignment(GV.getAlign());
1345 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1346 if (GV.hasSection()) {
1347 // Give section names unique ID's.
1348 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1349 if (!Entry) {
1350 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1351 0 /*TODO*/);
1352 Entry = SectionMap.size();
1353 }
1354 }
1355 }
1356 for (const Function &F : M) {
1357 UpdateMaxAlignment(F.getAlign());
1358 if (F.hasSection()) {
1359 // Give section names unique ID's.
1360 unsigned &Entry = SectionMap[std::string(F.getSection())];
1361 if (!Entry) {
1363 0 /*TODO*/);
1364 Entry = SectionMap.size();
1365 }
1366 }
1367 if (F.hasGC()) {
1368 // Same for GC names.
1369 unsigned &Entry = GCMap[F.getGC()];
1370 if (!Entry) {
1372 0 /*TODO*/);
1373 Entry = GCMap.size();
1374 }
1375 }
1376 }
1377
1378 // Emit abbrev for globals, now that we know # sections and max alignment.
1379 unsigned SimpleGVarAbbrev = 0;
1380 if (!M.global_empty()) {
1381 // Add an abbrev for common globals with no visibility or thread localness.
1382 auto Abbv = std::make_shared<BitCodeAbbrev>();
1387 Log2_32_Ceil(MaxGlobalType+1)));
1388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1389 //| explicitType << 1
1390 //| constant
1391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1392 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1393 if (!MaxAlignment) // Alignment.
1394 Abbv->Add(BitCodeAbbrevOp(0));
1395 else {
1396 unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1398 Log2_32_Ceil(MaxEncAlignment+1)));
1399 }
1400 if (SectionMap.empty()) // Section.
1401 Abbv->Add(BitCodeAbbrevOp(0));
1402 else
1404 Log2_32_Ceil(SectionMap.size()+1)));
1405 // Don't bother emitting vis + thread local.
1406 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1407 }
1408
1410 // Emit the module's source file name.
1411 {
1412 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1414 if (Bits == SE_Char6)
1415 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1416 else if (Bits == SE_Fixed7)
1417 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1418
1419 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1420 auto Abbv = std::make_shared<BitCodeAbbrev>();
1423 Abbv->Add(AbbrevOpToUse);
1424 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1425
1426 for (const auto P : M.getSourceFileName())
1427 Vals.push_back((unsigned char)P);
1428
1429 // Emit the finished record.
1430 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1431 Vals.clear();
1432 }
1433
1434 // Emit the global variable information.
1435 for (const GlobalVariable &GV : M.globals()) {
1436 unsigned AbbrevToUse = 0;
1437
1438 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1439 // linkage, alignment, section, visibility, threadlocal,
1440 // unnamed_addr, externally_initialized, dllstorageclass,
1441 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1442 Vals.push_back(addToStrtab(GV.getName()));
1443 Vals.push_back(GV.getName().size());
1444 Vals.push_back(VE.getTypeID(GV.getValueType()));
1445 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1446 Vals.push_back(GV.isDeclaration() ? 0 :
1447 (VE.getValueID(GV.getInitializer()) + 1));
1448 Vals.push_back(getEncodedLinkage(GV));
1449 Vals.push_back(getEncodedAlign(GV.getAlign()));
1450 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1451 : 0);
1452 if (GV.isThreadLocal() ||
1453 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1454 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1455 GV.isExternallyInitialized() ||
1456 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1457 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1458 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1462 Vals.push_back(GV.isExternallyInitialized());
1464 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1465
1466 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1467 Vals.push_back(VE.getAttributeListID(AL));
1468
1469 Vals.push_back(GV.isDSOLocal());
1470 Vals.push_back(addToStrtab(GV.getPartition()));
1471 Vals.push_back(GV.getPartition().size());
1472
1473 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1474 GV.getSanitizerMetadata())
1475 : 0));
1476 Vals.push_back(GV.getCodeModelRaw());
1477 } else {
1478 AbbrevToUse = SimpleGVarAbbrev;
1479 }
1480
1481 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1482 Vals.clear();
1483 }
1484
1485 // Emit the function proto information.
1486 for (const Function &F : M) {
1487 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1488 // linkage, paramattrs, alignment, section, visibility, gc,
1489 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1490 // prefixdata, personalityfn, DSO_Local, addrspace]
1491 Vals.push_back(addToStrtab(F.getName()));
1492 Vals.push_back(F.getName().size());
1493 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1494 Vals.push_back(F.getCallingConv());
1495 Vals.push_back(F.isDeclaration());
1497 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1498 Vals.push_back(getEncodedAlign(F.getAlign()));
1499 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1500 : 0);
1502 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1504 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1505 : 0);
1507 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1508 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1509 : 0);
1510 Vals.push_back(
1511 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1512
1513 Vals.push_back(F.isDSOLocal());
1514 Vals.push_back(F.getAddressSpace());
1515 Vals.push_back(addToStrtab(F.getPartition()));
1516 Vals.push_back(F.getPartition().size());
1517
1518 unsigned AbbrevToUse = 0;
1519 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1520 Vals.clear();
1521 }
1522
1523 // Emit the alias information.
1524 for (const GlobalAlias &A : M.aliases()) {
1525 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1526 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1527 // DSO_Local]
1528 Vals.push_back(addToStrtab(A.getName()));
1529 Vals.push_back(A.getName().size());
1530 Vals.push_back(VE.getTypeID(A.getValueType()));
1531 Vals.push_back(A.getType()->getAddressSpace());
1532 Vals.push_back(VE.getValueID(A.getAliasee()));
1538 Vals.push_back(A.isDSOLocal());
1539 Vals.push_back(addToStrtab(A.getPartition()));
1540 Vals.push_back(A.getPartition().size());
1541
1542 unsigned AbbrevToUse = 0;
1543 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1544 Vals.clear();
1545 }
1546
1547 // Emit the ifunc information.
1548 for (const GlobalIFunc &I : M.ifuncs()) {
1549 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1550 // val#, linkage, visibility, DSO_Local]
1551 Vals.push_back(addToStrtab(I.getName()));
1552 Vals.push_back(I.getName().size());
1553 Vals.push_back(VE.getTypeID(I.getValueType()));
1554 Vals.push_back(I.getType()->getAddressSpace());
1555 Vals.push_back(VE.getValueID(I.getResolver()));
1558 Vals.push_back(I.isDSOLocal());
1559 Vals.push_back(addToStrtab(I.getPartition()));
1560 Vals.push_back(I.getPartition().size());
1561 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1562 Vals.clear();
1563 }
1564
1565 writeValueSymbolTableForwardDecl();
1566}
1567
1569 uint64_t Flags = 0;
1570
1571 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1572 if (OBO->hasNoSignedWrap())
1573 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1574 if (OBO->hasNoUnsignedWrap())
1575 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1576 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1577 if (PEO->isExact())
1578 Flags |= 1 << bitc::PEO_EXACT;
1579 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1580 if (PDI->isDisjoint())
1581 Flags |= 1 << bitc::PDI_DISJOINT;
1582 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1583 if (FPMO->hasAllowReassoc())
1584 Flags |= bitc::AllowReassoc;
1585 if (FPMO->hasNoNaNs())
1586 Flags |= bitc::NoNaNs;
1587 if (FPMO->hasNoInfs())
1588 Flags |= bitc::NoInfs;
1589 if (FPMO->hasNoSignedZeros())
1590 Flags |= bitc::NoSignedZeros;
1591 if (FPMO->hasAllowReciprocal())
1592 Flags |= bitc::AllowReciprocal;
1593 if (FPMO->hasAllowContract())
1594 Flags |= bitc::AllowContract;
1595 if (FPMO->hasApproxFunc())
1596 Flags |= bitc::ApproxFunc;
1597 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1598 if (NNI->hasNonNeg())
1599 Flags |= 1 << bitc::PNNI_NON_NEG;
1600 }
1601
1602 return Flags;
1603}
1604
1605void ModuleBitcodeWriter::writeValueAsMetadata(
1607 // Mimic an MDNode with a value as one operand.
1608 Value *V = MD->getValue();
1609 Record.push_back(VE.getTypeID(V->getType()));
1610 Record.push_back(VE.getValueID(V));
1612 Record.clear();
1613}
1614
1615void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1617 unsigned Abbrev) {
1618 for (const MDOperand &MDO : N->operands()) {
1619 Metadata *MD = MDO;
1620 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1621 "Unexpected function-local metadata");
1622 Record.push_back(VE.getMetadataOrNullID(MD));
1623 }
1624 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1626 Record, Abbrev);
1627 Record.clear();
1628}
1629
1630unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1631 // Assume the column is usually under 128, and always output the inlined-at
1632 // location (it's never more expensive than building an array size 1).
1633 auto Abbv = std::make_shared<BitCodeAbbrev>();
1641 return Stream.EmitAbbrev(std::move(Abbv));
1642}
1643
1644void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1646 unsigned &Abbrev) {
1647 if (!Abbrev)
1648 Abbrev = createDILocationAbbrev();
1649
1650 Record.push_back(N->isDistinct());
1651 Record.push_back(N->getLine());
1652 Record.push_back(N->getColumn());
1653 Record.push_back(VE.getMetadataID(N->getScope()));
1654 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1655 Record.push_back(N->isImplicitCode());
1656
1657 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1658 Record.clear();
1659}
1660
1661unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1662 // Assume the column is usually under 128, and always output the inlined-at
1663 // location (it's never more expensive than building an array size 1).
1664 auto Abbv = std::make_shared<BitCodeAbbrev>();
1672 return Stream.EmitAbbrev(std::move(Abbv));
1673}
1674
1675void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1677 unsigned &Abbrev) {
1678 if (!Abbrev)
1679 Abbrev = createGenericDINodeAbbrev();
1680
1681 Record.push_back(N->isDistinct());
1682 Record.push_back(N->getTag());
1683 Record.push_back(0); // Per-tag version field; unused for now.
1684
1685 for (auto &I : N->operands())
1686 Record.push_back(VE.getMetadataOrNullID(I));
1687
1689 Record.clear();
1690}
1691
1692void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1694 unsigned Abbrev) {
1695 const uint64_t Version = 2 << 1;
1696 Record.push_back((uint64_t)N->isDistinct() | Version);
1697 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1698 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1699 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1700 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1701
1702 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1703 Record.clear();
1704}
1705
1706void ModuleBitcodeWriter::writeDIGenericSubrange(
1708 unsigned Abbrev) {
1709 Record.push_back((uint64_t)N->isDistinct());
1710 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1711 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1712 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1713 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1714
1716 Record.clear();
1717}
1718
1720 if ((int64_t)V >= 0)
1721 Vals.push_back(V << 1);
1722 else
1723 Vals.push_back((-V << 1) | 1);
1724}
1725
1727 // We have an arbitrary precision integer value to write whose
1728 // bit width is > 64. However, in canonical unsigned integer
1729 // format it is likely that the high bits are going to be zero.
1730 // So, we only write the number of active words.
1731 unsigned NumWords = A.getActiveWords();
1732 const uint64_t *RawData = A.getRawData();
1733 for (unsigned i = 0; i < NumWords; i++)
1734 emitSignedInt64(Vals, RawData[i]);
1735}
1736
1737void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1739 unsigned Abbrev) {
1740 const uint64_t IsBigInt = 1 << 2;
1741 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1742 Record.push_back(N->getValue().getBitWidth());
1743 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1744 emitWideAPInt(Record, N->getValue());
1745
1747 Record.clear();
1748}
1749
1750void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1752 unsigned Abbrev) {
1753 Record.push_back(N->isDistinct());
1754 Record.push_back(N->getTag());
1755 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1756 Record.push_back(N->getSizeInBits());
1757 Record.push_back(N->getAlignInBits());
1758 Record.push_back(N->getEncoding());
1759 Record.push_back(N->getFlags());
1760
1762 Record.clear();
1763}
1764
1765void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1767 unsigned Abbrev) {
1768 Record.push_back(N->isDistinct());
1769 Record.push_back(N->getTag());
1770 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1771 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1772 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1773 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1774 Record.push_back(N->getSizeInBits());
1775 Record.push_back(N->getAlignInBits());
1776 Record.push_back(N->getEncoding());
1777
1779 Record.clear();
1780}
1781
1782void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1784 unsigned Abbrev) {
1785 Record.push_back(N->isDistinct());
1786 Record.push_back(N->getTag());
1787 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1788 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1789 Record.push_back(N->getLine());
1790 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1791 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1792 Record.push_back(N->getSizeInBits());
1793 Record.push_back(N->getAlignInBits());
1794 Record.push_back(N->getOffsetInBits());
1795 Record.push_back(N->getFlags());
1796 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1797
1798 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1799 // that there is no DWARF address space associated with DIDerivedType.
1800 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1801 Record.push_back(*DWARFAddressSpace + 1);
1802 else
1803 Record.push_back(0);
1804
1805 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1806
1808 Record.clear();
1809}
1810
1811void ModuleBitcodeWriter::writeDICompositeType(
1813 unsigned Abbrev) {
1814 const unsigned IsNotUsedInOldTypeRef = 0x2;
1815 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1816 Record.push_back(N->getTag());
1817 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1818 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1819 Record.push_back(N->getLine());
1820 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1821 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1822 Record.push_back(N->getSizeInBits());
1823 Record.push_back(N->getAlignInBits());
1824 Record.push_back(N->getOffsetInBits());
1825 Record.push_back(N->getFlags());
1826 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1827 Record.push_back(N->getRuntimeLang());
1828 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1829 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1830 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1831 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1832 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1833 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1834 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1835 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1836 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1837
1839 Record.clear();
1840}
1841
1842void ModuleBitcodeWriter::writeDISubroutineType(
1844 unsigned Abbrev) {
1845 const unsigned HasNoOldTypeRefs = 0x2;
1846 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1847 Record.push_back(N->getFlags());
1848 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1849 Record.push_back(N->getCC());
1850
1852 Record.clear();
1853}
1854
1855void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1857 unsigned Abbrev) {
1858 Record.push_back(N->isDistinct());
1859 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1860 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1861 if (N->getRawChecksum()) {
1862 Record.push_back(N->getRawChecksum()->Kind);
1863 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1864 } else {
1865 // Maintain backwards compatibility with the old internal representation of
1866 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1867 Record.push_back(0);
1868 Record.push_back(VE.getMetadataOrNullID(nullptr));
1869 }
1870 auto Source = N->getRawSource();
1871 if (Source)
1872 Record.push_back(VE.getMetadataOrNullID(Source));
1873
1874 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1875 Record.clear();
1876}
1877
1878void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1880 unsigned Abbrev) {
1881 assert(N->isDistinct() && "Expected distinct compile units");
1882 Record.push_back(/* IsDistinct */ true);
1883 Record.push_back(N->getSourceLanguage());
1884 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1885 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1886 Record.push_back(N->isOptimized());
1887 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1888 Record.push_back(N->getRuntimeVersion());
1889 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1890 Record.push_back(N->getEmissionKind());
1891 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1892 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1893 Record.push_back(/* subprograms */ 0);
1894 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1895 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1896 Record.push_back(N->getDWOId());
1897 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1898 Record.push_back(N->getSplitDebugInlining());
1899 Record.push_back(N->getDebugInfoForProfiling());
1900 Record.push_back((unsigned)N->getNameTableKind());
1901 Record.push_back(N->getRangesBaseAddress());
1902 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1903 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1904
1906 Record.clear();
1907}
1908
1909void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1911 unsigned Abbrev) {
1912 const uint64_t HasUnitFlag = 1 << 1;
1913 const uint64_t HasSPFlagsFlag = 1 << 2;
1914 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1915 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1916 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1917 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1918 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1919 Record.push_back(N->getLine());
1920 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1921 Record.push_back(N->getScopeLine());
1922 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1923 Record.push_back(N->getSPFlags());
1924 Record.push_back(N->getVirtualIndex());
1925 Record.push_back(N->getFlags());
1926 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1927 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1928 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1929 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1930 Record.push_back(N->getThisAdjustment());
1931 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1932 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1933 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
1934
1936 Record.clear();
1937}
1938
1939void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1941 unsigned Abbrev) {
1942 Record.push_back(N->isDistinct());
1943 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1944 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1945 Record.push_back(N->getLine());
1946 Record.push_back(N->getColumn());
1947
1949 Record.clear();
1950}
1951
1952void ModuleBitcodeWriter::writeDILexicalBlockFile(
1954 unsigned Abbrev) {
1955 Record.push_back(N->isDistinct());
1956 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1957 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1958 Record.push_back(N->getDiscriminator());
1959
1961 Record.clear();
1962}
1963
1964void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
1966 unsigned Abbrev) {
1967 Record.push_back(N->isDistinct());
1968 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1969 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1970 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1971 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1972 Record.push_back(N->getLineNo());
1973
1975 Record.clear();
1976}
1977
1978void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1980 unsigned Abbrev) {
1981 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1982 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1983 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1984
1986 Record.clear();
1987}
1988
1989void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1991 unsigned Abbrev) {
1992 Record.push_back(N->isDistinct());
1993 Record.push_back(N->getMacinfoType());
1994 Record.push_back(N->getLine());
1995 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1996 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1997
1998 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1999 Record.clear();
2000}
2001
2002void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2004 unsigned Abbrev) {
2005 Record.push_back(N->isDistinct());
2006 Record.push_back(N->getMacinfoType());
2007 Record.push_back(N->getLine());
2008 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2009 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2010
2012 Record.clear();
2013}
2014
2015void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2017 Record.reserve(N->getArgs().size());
2018 for (ValueAsMetadata *MD : N->getArgs())
2019 Record.push_back(VE.getMetadataID(MD));
2020
2022 Record.clear();
2023}
2024
2025void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2027 unsigned Abbrev) {
2028 Record.push_back(N->isDistinct());
2029 for (auto &I : N->operands())
2030 Record.push_back(VE.getMetadataOrNullID(I));
2031 Record.push_back(N->getLineNo());
2032 Record.push_back(N->getIsDecl());
2033
2034 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2035 Record.clear();
2036}
2037
2038void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2040 unsigned Abbrev) {
2041 // There are no arguments for this metadata type.
2042 Record.push_back(N->isDistinct());
2044 Record.clear();
2045}
2046
2047void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2049 unsigned Abbrev) {
2050 Record.push_back(N->isDistinct());
2051 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2052 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2053 Record.push_back(N->isDefault());
2054
2056 Record.clear();
2057}
2058
2059void ModuleBitcodeWriter::writeDITemplateValueParameter(
2061 unsigned Abbrev) {
2062 Record.push_back(N->isDistinct());
2063 Record.push_back(N->getTag());
2064 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2065 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2066 Record.push_back(N->isDefault());
2067 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2068
2070 Record.clear();
2071}
2072
2073void ModuleBitcodeWriter::writeDIGlobalVariable(
2075 unsigned Abbrev) {
2076 const uint64_t Version = 2 << 1;
2077 Record.push_back((uint64_t)N->isDistinct() | Version);
2078 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2079 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2080 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2081 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2082 Record.push_back(N->getLine());
2083 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2084 Record.push_back(N->isLocalToUnit());
2085 Record.push_back(N->isDefinition());
2086 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2087 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2088 Record.push_back(N->getAlignInBits());
2089 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2090
2092 Record.clear();
2093}
2094
2095void ModuleBitcodeWriter::writeDILocalVariable(
2097 unsigned Abbrev) {
2098 // In order to support all possible bitcode formats in BitcodeReader we need
2099 // to distinguish the following cases:
2100 // 1) Record has no artificial tag (Record[1]),
2101 // has no obsolete inlinedAt field (Record[9]).
2102 // In this case Record size will be 8, HasAlignment flag is false.
2103 // 2) Record has artificial tag (Record[1]),
2104 // has no obsolete inlignedAt field (Record[9]).
2105 // In this case Record size will be 9, HasAlignment flag is false.
2106 // 3) Record has both artificial tag (Record[1]) and
2107 // obsolete inlignedAt field (Record[9]).
2108 // In this case Record size will be 10, HasAlignment flag is false.
2109 // 4) Record has neither artificial tag, nor inlignedAt field, but
2110 // HasAlignment flag is true and Record[8] contains alignment value.
2111 const uint64_t HasAlignmentFlag = 1 << 1;
2112 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2113 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2114 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2115 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2116 Record.push_back(N->getLine());
2117 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2118 Record.push_back(N->getArg());
2119 Record.push_back(N->getFlags());
2120 Record.push_back(N->getAlignInBits());
2121 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2122
2124 Record.clear();
2125}
2126
2127void ModuleBitcodeWriter::writeDILabel(
2129 unsigned Abbrev) {
2130 Record.push_back((uint64_t)N->isDistinct());
2131 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2132 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2133 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2134 Record.push_back(N->getLine());
2135
2136 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2137 Record.clear();
2138}
2139
2140void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2142 unsigned Abbrev) {
2143 Record.reserve(N->getElements().size() + 1);
2144 const uint64_t Version = 3 << 1;
2145 Record.push_back((uint64_t)N->isDistinct() | Version);
2146 Record.append(N->elements_begin(), N->elements_end());
2147
2149 Record.clear();
2150}
2151
2152void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2154 unsigned Abbrev) {
2155 Record.push_back(N->isDistinct());
2156 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2157 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2158
2160 Record.clear();
2161}
2162
2163void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2165 unsigned Abbrev) {
2166 Record.push_back(N->isDistinct());
2167 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2168 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2169 Record.push_back(N->getLine());
2170 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2171 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2172 Record.push_back(N->getAttributes());
2173 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2174
2176 Record.clear();
2177}
2178
2179void ModuleBitcodeWriter::writeDIImportedEntity(
2181 unsigned Abbrev) {
2182 Record.push_back(N->isDistinct());
2183 Record.push_back(N->getTag());
2184 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2185 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2186 Record.push_back(N->getLine());
2187 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2188 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2189 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2190
2192 Record.clear();
2193}
2194
2195unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2196 auto Abbv = std::make_shared<BitCodeAbbrev>();
2200 return Stream.EmitAbbrev(std::move(Abbv));
2201}
2202
2203void ModuleBitcodeWriter::writeNamedMetadata(
2205 if (M.named_metadata_empty())
2206 return;
2207
2208 unsigned Abbrev = createNamedMetadataAbbrev();
2209 for (const NamedMDNode &NMD : M.named_metadata()) {
2210 // Write name.
2211 StringRef Str = NMD.getName();
2212 Record.append(Str.bytes_begin(), Str.bytes_end());
2213 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2214 Record.clear();
2215
2216 // Write named metadata operands.
2217 for (const MDNode *N : NMD.operands())
2218 Record.push_back(VE.getMetadataID(N));
2220 Record.clear();
2221 }
2222}
2223
2224unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2225 auto Abbv = std::make_shared<BitCodeAbbrev>();
2227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2230 return Stream.EmitAbbrev(std::move(Abbv));
2231}
2232
2233/// Write out a record for MDString.
2234///
2235/// All the metadata strings in a metadata block are emitted in a single
2236/// record. The sizes and strings themselves are shoved into a blob.
2237void ModuleBitcodeWriter::writeMetadataStrings(
2239 if (Strings.empty())
2240 return;
2241
2242 // Start the record with the number of strings.
2243 Record.push_back(bitc::METADATA_STRINGS);
2244 Record.push_back(Strings.size());
2245
2246 // Emit the sizes of the strings in the blob.
2247 SmallString<256> Blob;
2248 {
2249 BitstreamWriter W(Blob);
2250 for (const Metadata *MD : Strings)
2251 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2252 W.FlushToWord();
2253 }
2254
2255 // Add the offset to the strings to the record.
2256 Record.push_back(Blob.size());
2257
2258 // Add the strings to the blob.
2259 for (const Metadata *MD : Strings)
2260 Blob.append(cast<MDString>(MD)->getString());
2261
2262 // Emit the final record.
2263 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2264 Record.clear();
2265}
2266
2267// Generates an enum to use as an index in the Abbrev array of Metadata record.
2268enum MetadataAbbrev : unsigned {
2269#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2270#include "llvm/IR/Metadata.def"
2273
2274void ModuleBitcodeWriter::writeMetadataRecords(
2276 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2277 if (MDs.empty())
2278 return;
2279
2280 // Initialize MDNode abbreviations.
2281#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2282#include "llvm/IR/Metadata.def"
2283
2284 for (const Metadata *MD : MDs) {
2285 if (IndexPos)
2286 IndexPos->push_back(Stream.GetCurrentBitNo());
2287 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2288 assert(N->isResolved() && "Expected forward references to be resolved");
2289
2290 switch (N->getMetadataID()) {
2291 default:
2292 llvm_unreachable("Invalid MDNode subclass");
2293#define HANDLE_MDNODE_LEAF(CLASS) \
2294 case Metadata::CLASS##Kind: \
2295 if (MDAbbrevs) \
2296 write##CLASS(cast<CLASS>(N), Record, \
2297 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2298 else \
2299 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2300 continue;
2301#include "llvm/IR/Metadata.def"
2302 }
2303 }
2304 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2306 continue;
2307 }
2308 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2309 }
2310}
2311
2312void ModuleBitcodeWriter::writeModuleMetadata() {
2313 if (!VE.hasMDs() && M.named_metadata_empty())
2314 return;
2315
2318
2319 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2320 // block and load any metadata.
2321 std::vector<unsigned> MDAbbrevs;
2322
2323 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2324 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2325 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2326 createGenericDINodeAbbrev();
2327
2328 auto Abbv = std::make_shared<BitCodeAbbrev>();
2332 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2333
2334 Abbv = std::make_shared<BitCodeAbbrev>();
2338 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2339
2340 // Emit MDStrings together upfront.
2341 writeMetadataStrings(VE.getMDStrings(), Record);
2342
2343 // We only emit an index for the metadata record if we have more than a given
2344 // (naive) threshold of metadatas, otherwise it is not worth it.
2345 if (VE.getNonMDStrings().size() > IndexThreshold) {
2346 // Write a placeholder value in for the offset of the metadata index,
2347 // which is written after the records, so that it can include
2348 // the offset of each entry. The placeholder offset will be
2349 // updated after all records are emitted.
2350 uint64_t Vals[] = {0, 0};
2351 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2352 }
2353
2354 // Compute and save the bit offset to the current position, which will be
2355 // patched when we emit the index later. We can simply subtract the 64-bit
2356 // fixed size from the current bit number to get the location to backpatch.
2357 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2358
2359 // This index will contain the bitpos for each individual record.
2360 std::vector<uint64_t> IndexPos;
2361 IndexPos.reserve(VE.getNonMDStrings().size());
2362
2363 // Write all the records
2364 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2365
2366 if (VE.getNonMDStrings().size() > IndexThreshold) {
2367 // Now that we have emitted all the records we will emit the index. But
2368 // first
2369 // backpatch the forward reference so that the reader can skip the records
2370 // efficiently.
2371 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2372 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2373
2374 // Delta encode the index.
2375 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2376 for (auto &Elt : IndexPos) {
2377 auto EltDelta = Elt - PreviousValue;
2378 PreviousValue = Elt;
2379 Elt = EltDelta;
2380 }
2381 // Emit the index record.
2382 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2383 IndexPos.clear();
2384 }
2385
2386 // Write the named metadata now.
2387 writeNamedMetadata(Record);
2388
2389 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2391 Record.push_back(VE.getValueID(&GO));
2392 pushGlobalMetadataAttachment(Record, GO);
2394 };
2395 for (const Function &F : M)
2396 if (F.isDeclaration() && F.hasMetadata())
2397 AddDeclAttachedMetadata(F);
2398 // FIXME: Only store metadata for declarations here, and move data for global
2399 // variable definitions to a separate block (PR28134).
2400 for (const GlobalVariable &GV : M.globals())
2401 if (GV.hasMetadata())
2402 AddDeclAttachedMetadata(GV);
2403
2404 Stream.ExitBlock();
2405}
2406
2407void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2408 if (!VE.hasMDs())
2409 return;
2410
2413 writeMetadataStrings(VE.getMDStrings(), Record);
2414 writeMetadataRecords(VE.getNonMDStrings(), Record);
2415 Stream.ExitBlock();
2416}
2417
2418void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2420 // [n x [id, mdnode]]
2422 GO.getAllMetadata(MDs);
2423 for (const auto &I : MDs) {
2424 Record.push_back(I.first);
2425 Record.push_back(VE.getMetadataID(I.second));
2426 }
2427}
2428
2429void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2431
2433
2434 if (F.hasMetadata()) {
2435 pushGlobalMetadataAttachment(Record, F);
2437 Record.clear();
2438 }
2439
2440 // Write metadata attachments
2441 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2443 for (const BasicBlock &BB : F)
2444 for (const Instruction &I : BB) {
2445 MDs.clear();
2446 I.getAllMetadataOtherThanDebugLoc(MDs);
2447
2448 // If no metadata, ignore instruction.
2449 if (MDs.empty()) continue;
2450
2451 Record.push_back(VE.getInstructionID(&I));
2452
2453 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2454 Record.push_back(MDs[i].first);
2455 Record.push_back(VE.getMetadataID(MDs[i].second));
2456 }
2458 Record.clear();
2459 }
2460
2461 Stream.ExitBlock();
2462}
2463
2464void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2466
2467 // Write metadata kinds
2468 // METADATA_KIND - [n x [id, name]]
2470 M.getMDKindNames(Names);
2471
2472 if (Names.empty()) return;
2473
2475
2476 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2477 Record.push_back(MDKindID);
2478 StringRef KName = Names[MDKindID];
2479 Record.append(KName.begin(), KName.end());
2480
2482 Record.clear();
2483 }
2484
2485 Stream.ExitBlock();
2486}
2487
2488void ModuleBitcodeWriter::writeOperandBundleTags() {
2489 // Write metadata kinds
2490 //
2491 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2492 //
2493 // OPERAND_BUNDLE_TAG - [strchr x N]
2494
2496 M.getOperandBundleTags(Tags);
2497
2498 if (Tags.empty())
2499 return;
2500
2502
2504
2505 for (auto Tag : Tags) {
2506 Record.append(Tag.begin(), Tag.end());
2507
2509 Record.clear();
2510 }
2511
2512 Stream.ExitBlock();
2513}
2514
2515void ModuleBitcodeWriter::writeSyncScopeNames() {
2517 M.getContext().getSyncScopeNames(SSNs);
2518 if (SSNs.empty())
2519 return;
2520
2522
2524 for (auto SSN : SSNs) {
2525 Record.append(SSN.begin(), SSN.end());
2527 Record.clear();
2528 }
2529
2530 Stream.ExitBlock();
2531}
2532
2533void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2534 bool isGlobal) {
2535 if (FirstVal == LastVal) return;
2536
2538
2539 unsigned AggregateAbbrev = 0;
2540 unsigned String8Abbrev = 0;
2541 unsigned CString7Abbrev = 0;
2542 unsigned CString6Abbrev = 0;
2543 // If this is a constant pool for the module, emit module-specific abbrevs.
2544 if (isGlobal) {
2545 // Abbrev for CST_CODE_AGGREGATE.
2546 auto Abbv = std::make_shared<BitCodeAbbrev>();
2549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2550 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2551
2552 // Abbrev for CST_CODE_STRING.
2553 Abbv = std::make_shared<BitCodeAbbrev>();
2557 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2558 // Abbrev for CST_CODE_CSTRING.
2559 Abbv = std::make_shared<BitCodeAbbrev>();
2563 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2564 // Abbrev for CST_CODE_CSTRING.
2565 Abbv = std::make_shared<BitCodeAbbrev>();
2569 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2570 }
2571
2573
2574 const ValueEnumerator::ValueList &Vals = VE.getValues();
2575 Type *LastTy = nullptr;
2576 for (unsigned i = FirstVal; i != LastVal; ++i) {
2577 const Value *V = Vals[i].first;
2578 // If we need to switch types, do so now.
2579 if (V->getType() != LastTy) {
2580 LastTy = V->getType();
2581 Record.push_back(VE.getTypeID(LastTy));
2583 CONSTANTS_SETTYPE_ABBREV);
2584 Record.clear();
2585 }
2586
2587 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2588 Record.push_back(VE.getTypeID(IA->getFunctionType()));
2589 Record.push_back(
2590 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2591 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2592
2593 // Add the asm string.
2594 const std::string &AsmStr = IA->getAsmString();
2595 Record.push_back(AsmStr.size());
2596 Record.append(AsmStr.begin(), AsmStr.end());
2597
2598 // Add the constraint string.
2599 const std::string &ConstraintStr = IA->getConstraintString();
2600 Record.push_back(ConstraintStr.size());
2601 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2603 Record.clear();
2604 continue;
2605 }
2606 const Constant *C = cast<Constant>(V);
2607 unsigned Code = -1U;
2608 unsigned AbbrevToUse = 0;
2609 if (C->isNullValue()) {
2611 } else if (isa<PoisonValue>(C)) {
2613 } else if (isa<UndefValue>(C)) {
2615 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2616 if (IV->getBitWidth() <= 64) {
2617 uint64_t V = IV->getSExtValue();
2620 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2621 } else { // Wide integers, > 64 bits in size.
2622 emitWideAPInt(Record, IV->getValue());
2624 }
2625 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2627 Type *Ty = CFP->getType()->getScalarType();
2628 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2629 Ty->isDoubleTy()) {
2630 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2631 } else if (Ty->isX86_FP80Ty()) {
2632 // api needed to prevent premature destruction
2633 // bits are not in the same order as a normal i80 APInt, compensate.
2634 APInt api = CFP->getValueAPF().bitcastToAPInt();
2635 const uint64_t *p = api.getRawData();
2636 Record.push_back((p[1] << 48) | (p[0] >> 16));
2637 Record.push_back(p[0] & 0xffffLL);
2638 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2639 APInt api = CFP->getValueAPF().bitcastToAPInt();
2640 const uint64_t *p = api.getRawData();
2641 Record.push_back(p[0]);
2642 Record.push_back(p[1]);
2643 } else {
2644 assert(0 && "Unknown FP type!");
2645 }
2646 } else if (isa<ConstantDataSequential>(C) &&
2647 cast<ConstantDataSequential>(C)->isString()) {
2648 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2649 // Emit constant strings specially.
2650 unsigned NumElts = Str->getNumElements();
2651 // If this is a null-terminated string, use the denser CSTRING encoding.
2652 if (Str->isCString()) {
2654 --NumElts; // Don't encode the null, which isn't allowed by char6.
2655 } else {
2657 AbbrevToUse = String8Abbrev;
2658 }
2659 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2660 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2661 for (unsigned i = 0; i != NumElts; ++i) {
2662 unsigned char V = Str->getElementAsInteger(i);
2663 Record.push_back(V);
2664 isCStr7 &= (V & 128) == 0;
2665 if (isCStrChar6)
2666 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2667 }
2668
2669 if (isCStrChar6)
2670 AbbrevToUse = CString6Abbrev;
2671 else if (isCStr7)
2672 AbbrevToUse = CString7Abbrev;
2673 } else if (const ConstantDataSequential *CDS =
2674 dyn_cast<ConstantDataSequential>(C)) {
2676 Type *EltTy = CDS->getElementType();
2677 if (isa<IntegerType>(EltTy)) {
2678 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2679 Record.push_back(CDS->getElementAsInteger(i));
2680 } else {
2681 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2682 Record.push_back(
2683 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2684 }
2685 } else if (isa<ConstantAggregate>(C)) {
2687 for (const Value *Op : C->operands())
2688 Record.push_back(VE.getValueID(Op));
2689 AbbrevToUse = AggregateAbbrev;
2690 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2691 switch (CE->getOpcode()) {
2692 default:
2693 if (Instruction::isCast(CE->getOpcode())) {
2695 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2696 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2697 Record.push_back(VE.getValueID(C->getOperand(0)));
2698 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2699 } else {
2700 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2702 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2703 Record.push_back(VE.getValueID(C->getOperand(0)));
2704 Record.push_back(VE.getValueID(C->getOperand(1)));
2706 if (Flags != 0)
2707 Record.push_back(Flags);
2708 }
2709 break;
2710 case Instruction::FNeg: {
2711 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2713 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2714 Record.push_back(VE.getValueID(C->getOperand(0)));
2716 if (Flags != 0)
2717 Record.push_back(Flags);
2718 break;
2719 }
2720 case Instruction::GetElementPtr: {
2722 const auto *GO = cast<GEPOperator>(C);
2723 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2724 if (std::optional<unsigned> Idx = GO->getInRangeIndex()) {
2726 Record.push_back((*Idx << 1) | GO->isInBounds());
2727 } else if (GO->isInBounds())
2729 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2730 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2731 Record.push_back(VE.getValueID(C->getOperand(i)));
2732 }
2733 break;
2734 }
2735 case Instruction::ExtractElement:
2737 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2738 Record.push_back(VE.getValueID(C->getOperand(0)));
2739 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2740 Record.push_back(VE.getValueID(C->getOperand(1)));
2741 break;
2742 case Instruction::InsertElement:
2744 Record.push_back(VE.getValueID(C->getOperand(0)));
2745 Record.push_back(VE.getValueID(C->getOperand(1)));
2746 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2747 Record.push_back(VE.getValueID(C->getOperand(2)));
2748 break;
2749 case Instruction::ShuffleVector:
2750 // If the return type and argument types are the same, this is a
2751 // standard shufflevector instruction. If the types are different,
2752 // then the shuffle is widening or truncating the input vectors, and
2753 // the argument type must also be encoded.
2754 if (C->getType() == C->getOperand(0)->getType()) {
2756 } else {
2758 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2759 }
2760 Record.push_back(VE.getValueID(C->getOperand(0)));
2761 Record.push_back(VE.getValueID(C->getOperand(1)));
2762 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2763 break;
2764 case Instruction::ICmp:
2765 case Instruction::FCmp:
2767 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2768 Record.push_back(VE.getValueID(C->getOperand(0)));
2769 Record.push_back(VE.getValueID(C->getOperand(1)));
2770 Record.push_back(CE->getPredicate());
2771 break;
2772 }
2773 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2775 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2776 Record.push_back(VE.getValueID(BA->getFunction()));
2777 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2778 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2780 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2781 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2782 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2784 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2785 Record.push_back(VE.getValueID(NC->getGlobalValue()));
2786 } else {
2787#ifndef NDEBUG
2788 C->dump();
2789#endif
2790 llvm_unreachable("Unknown constant!");
2791 }
2792 Stream.EmitRecord(Code, Record, AbbrevToUse);
2793 Record.clear();
2794 }
2795
2796 Stream.ExitBlock();
2797}
2798
2799void ModuleBitcodeWriter::writeModuleConstants() {
2800 const ValueEnumerator::ValueList &Vals = VE.getValues();
2801
2802 // Find the first constant to emit, which is the first non-globalvalue value.
2803 // We know globalvalues have been emitted by WriteModuleInfo.
2804 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2805 if (!isa<GlobalValue>(Vals[i].first)) {
2806 writeConstants(i, Vals.size(), true);
2807 return;
2808 }
2809 }
2810}
2811
2812/// pushValueAndType - The file has to encode both the value and type id for
2813/// many values, because we need to know what type to create for forward
2814/// references. However, most operands are not forward references, so this type
2815/// field is not needed.
2816///
2817/// This function adds V's value ID to Vals. If the value ID is higher than the
2818/// instruction ID, then it is a forward reference, and it also includes the
2819/// type ID. The value ID that is written is encoded relative to the InstID.
2820bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2822 unsigned ValID = VE.getValueID(V);
2823 // Make encoding relative to the InstID.
2824 Vals.push_back(InstID - ValID);
2825 if (ValID >= InstID) {
2826 Vals.push_back(VE.getTypeID(V->getType()));
2827 return true;
2828 }
2829 return false;
2830}
2831
2832void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2833 unsigned InstID) {
2835 LLVMContext &C = CS.getContext();
2836
2837 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2838 const auto &Bundle = CS.getOperandBundleAt(i);
2839 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2840
2841 for (auto &Input : Bundle.Inputs)
2842 pushValueAndType(Input, InstID, Record);
2843
2845 Record.clear();
2846 }
2847}
2848
2849/// pushValue - Like pushValueAndType, but where the type of the value is
2850/// omitted (perhaps it was already encoded in an earlier operand).
2851void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2853 unsigned ValID = VE.getValueID(V);
2854 Vals.push_back(InstID - ValID);
2855}
2856
2857void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2859 unsigned ValID = VE.getValueID(V);
2860 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2861 emitSignedInt64(Vals, diff);
2862}
2863
2864/// WriteInstruction - Emit an instruction to the specified stream.
2865void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2866 unsigned InstID,
2868 unsigned Code = 0;
2869 unsigned AbbrevToUse = 0;
2870 VE.setInstructionID(&I);
2871 switch (I.getOpcode()) {
2872 default:
2873 if (Instruction::isCast(I.getOpcode())) {
2875 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2876 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2877 Vals.push_back(VE.getTypeID(I.getType()));
2878 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2880 if (Flags != 0) {
2881 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
2882 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
2883 Vals.push_back(Flags);
2884 }
2885 } else {
2886 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2888 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2889 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2890 pushValue(I.getOperand(1), InstID, Vals);
2891 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2893 if (Flags != 0) {
2894 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2895 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2896 Vals.push_back(Flags);
2897 }
2898 }
2899 break;
2900 case Instruction::FNeg: {
2902 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2903 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2904 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2906 if (Flags != 0) {
2907 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2908 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2909 Vals.push_back(Flags);
2910 }
2911 break;
2912 }
2913 case Instruction::GetElementPtr: {
2915 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2916 auto &GEPInst = cast<GetElementPtrInst>(I);
2917 Vals.push_back(GEPInst.isInBounds());
2918 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2919 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2920 pushValueAndType(I.getOperand(i), InstID, Vals);
2921 break;
2922 }
2923 case Instruction::ExtractValue: {
2925 pushValueAndType(I.getOperand(0), InstID, Vals);
2926 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2927 Vals.append(EVI->idx_begin(), EVI->idx_end());
2928 break;
2929 }
2930 case Instruction::InsertValue: {
2932 pushValueAndType(I.getOperand(0), InstID, Vals);
2933 pushValueAndType(I.getOperand(1), InstID, Vals);
2934 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2935 Vals.append(IVI->idx_begin(), IVI->idx_end());
2936 break;
2937 }
2938 case Instruction::Select: {
2940 pushValueAndType(I.getOperand(1), InstID, Vals);
2941 pushValue(I.getOperand(2), InstID, Vals);
2942 pushValueAndType(I.getOperand(0), InstID, Vals);
2944 if (Flags != 0)
2945 Vals.push_back(Flags);
2946 break;
2947 }
2948 case Instruction::ExtractElement:
2950 pushValueAndType(I.getOperand(0), InstID, Vals);
2951 pushValueAndType(I.getOperand(1), InstID, Vals);
2952 break;
2953 case Instruction::InsertElement:
2955 pushValueAndType(I.getOperand(0), InstID, Vals);
2956 pushValue(I.getOperand(1), InstID, Vals);
2957 pushValueAndType(I.getOperand(2), InstID, Vals);
2958 break;
2959 case Instruction::ShuffleVector:
2961 pushValueAndType(I.getOperand(0), InstID, Vals);
2962 pushValue(I.getOperand(1), InstID, Vals);
2963 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2964 Vals);
2965 break;
2966 case Instruction::ICmp:
2967 case Instruction::FCmp: {
2968 // compare returning Int1Ty or vector of Int1Ty
2970 pushValueAndType(I.getOperand(0), InstID, Vals);
2971 pushValue(I.getOperand(1), InstID, Vals);
2972 Vals.push_back(cast<CmpInst>(I).getPredicate());
2974 if (Flags != 0)
2975 Vals.push_back(Flags);
2976 break;
2977 }
2978
2979 case Instruction::Ret:
2980 {
2982 unsigned NumOperands = I.getNumOperands();
2983 if (NumOperands == 0)
2984 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2985 else if (NumOperands == 1) {
2986 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2987 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2988 } else {
2989 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2990 pushValueAndType(I.getOperand(i), InstID, Vals);
2991 }
2992 }
2993 break;
2994 case Instruction::Br:
2995 {
2997 const BranchInst &II = cast<BranchInst>(I);
2998 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2999 if (II.isConditional()) {
3000 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3001 pushValue(II.getCondition(), InstID, Vals);
3002 }
3003 }
3004 break;
3005 case Instruction::Switch:
3006 {
3008 const SwitchInst &SI = cast<SwitchInst>(I);
3009 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3010 pushValue(SI.getCondition(), InstID, Vals);
3011 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3012 for (auto Case : SI.cases()) {
3013 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3014 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3015 }
3016 }
3017 break;
3018 case Instruction::IndirectBr:
3020 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3021 // Encode the address operand as relative, but not the basic blocks.
3022 pushValue(I.getOperand(0), InstID, Vals);
3023 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
3024 Vals.push_back(VE.getValueID(I.getOperand(i)));
3025 break;
3026
3027 case Instruction::Invoke: {
3028 const InvokeInst *II = cast<InvokeInst>(&I);
3029 const Value *Callee = II->getCalledOperand();
3030 FunctionType *FTy = II->getFunctionType();
3031
3032 if (II->hasOperandBundles())
3033 writeOperandBundles(*II, InstID);
3034
3036
3038 Vals.push_back(II->getCallingConv() | 1 << 13);
3039 Vals.push_back(VE.getValueID(II->getNormalDest()));
3040 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3041 Vals.push_back(VE.getTypeID(FTy));
3042 pushValueAndType(Callee, InstID, Vals);
3043
3044 // Emit value #'s for the fixed parameters.
3045 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3046 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3047
3048 // Emit type/value pairs for varargs params.
3049 if (FTy->isVarArg()) {
3050 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3051 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3052 }
3053 break;
3054 }
3055 case Instruction::Resume:
3057 pushValueAndType(I.getOperand(0), InstID, Vals);
3058 break;
3059 case Instruction::CleanupRet: {
3061 const auto &CRI = cast<CleanupReturnInst>(I);
3062 pushValue(CRI.getCleanupPad(), InstID, Vals);
3063 if (CRI.hasUnwindDest())
3064 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3065 break;
3066 }
3067 case Instruction::CatchRet: {
3069 const auto &CRI = cast<CatchReturnInst>(I);
3070 pushValue(CRI.getCatchPad(), InstID, Vals);
3071 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3072 break;
3073 }
3074 case Instruction::CleanupPad:
3075 case Instruction::CatchPad: {
3076 const auto &FuncletPad = cast<FuncletPadInst>(I);
3077 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
3079 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3080
3081 unsigned NumArgOperands = FuncletPad.arg_size();
3082 Vals.push_back(NumArgOperands);
3083 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3084 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3085 break;
3086 }
3087 case Instruction::CatchSwitch: {
3089 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3090
3091 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3092
3093 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3094 Vals.push_back(NumHandlers);
3095 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3096 Vals.push_back(VE.getValueID(CatchPadBB));
3097
3098 if (CatchSwitch.hasUnwindDest())
3099 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3100 break;
3101 }
3102 case Instruction::CallBr: {
3103 const CallBrInst *CBI = cast<CallBrInst>(&I);
3104 const Value *Callee = CBI->getCalledOperand();
3105 FunctionType *FTy = CBI->getFunctionType();
3106
3107 if (CBI->hasOperandBundles())
3108 writeOperandBundles(*CBI, InstID);
3109
3111
3113
3116
3117 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3118 Vals.push_back(CBI->getNumIndirectDests());
3119 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3120 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3121
3122 Vals.push_back(VE.getTypeID(FTy));
3123 pushValueAndType(Callee, InstID, Vals);
3124
3125 // Emit value #'s for the fixed parameters.
3126 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3127 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3128
3129 // Emit type/value pairs for varargs params.
3130 if (FTy->isVarArg()) {
3131 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3132 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3133 }
3134 break;
3135 }
3136 case Instruction::Unreachable:
3138 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3139 break;
3140
3141 case Instruction::PHI: {
3142 const PHINode &PN = cast<PHINode>(I);
3144 // With the newer instruction encoding, forward references could give
3145 // negative valued IDs. This is most common for PHIs, so we use
3146 // signed VBRs.
3148 Vals64.push_back(VE.getTypeID(PN.getType()));
3149 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3150 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3151 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3152 }
3153
3155 if (Flags != 0)
3156 Vals64.push_back(Flags);
3157
3158 // Emit a Vals64 vector and exit.
3159 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3160 Vals64.clear();
3161 return;
3162 }
3163
3164 case Instruction::LandingPad: {
3165 const LandingPadInst &LP = cast<LandingPadInst>(I);
3167 Vals.push_back(VE.getTypeID(LP.getType()));
3168 Vals.push_back(LP.isCleanup());
3169 Vals.push_back(LP.getNumClauses());
3170 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3171 if (LP.isCatch(I))
3173 else
3175 pushValueAndType(LP.getClause(I), InstID, Vals);
3176 }
3177 break;
3178 }
3179
3180 case Instruction::Alloca: {
3182 const AllocaInst &AI = cast<AllocaInst>(I);
3183 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3184 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3185 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3186 using APV = AllocaPackedValues;
3187 unsigned Record = 0;
3188 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3189 Bitfield::set<APV::AlignLower>(
3190 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3191 Bitfield::set<APV::AlignUpper>(Record,
3192 EncodedAlign >> APV::AlignLower::Bits);
3193 Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3194 Bitfield::set<APV::ExplicitType>(Record, true);
3195 Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3196 Vals.push_back(Record);
3197
3198 unsigned AS = AI.getAddressSpace();
3199 if (AS != M.getDataLayout().getAllocaAddrSpace())
3200 Vals.push_back(AS);
3201 break;
3202 }
3203
3204 case Instruction::Load:
3205 if (cast<LoadInst>(I).isAtomic()) {
3207 pushValueAndType(I.getOperand(0), InstID, Vals);
3208 } else {
3210 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3211 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3212 }
3213 Vals.push_back(VE.getTypeID(I.getType()));
3214 Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3215 Vals.push_back(cast<LoadInst>(I).isVolatile());
3216 if (cast<LoadInst>(I).isAtomic()) {
3217 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3218 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3219 }
3220 break;
3221 case Instruction::Store:
3222 if (cast<StoreInst>(I).isAtomic())
3224 else
3226 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3227 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3228 Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3229 Vals.push_back(cast<StoreInst>(I).isVolatile());
3230 if (cast<StoreInst>(I).isAtomic()) {
3231 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3232 Vals.push_back(
3233 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3234 }
3235 break;
3236 case Instruction::AtomicCmpXchg:
3238 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3239 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3240 pushValue(I.getOperand(2), InstID, Vals); // newval.
3241 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3242 Vals.push_back(
3243 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3244 Vals.push_back(
3245 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3246 Vals.push_back(
3247 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3248 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3249 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3250 break;
3251 case Instruction::AtomicRMW:
3253 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3254 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3255 Vals.push_back(
3256 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3257 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3258 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3259 Vals.push_back(
3260 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3261 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3262 break;
3263 case Instruction::Fence:
3265 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3266 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3267 break;
3268 case Instruction::Call: {
3269 const CallInst &CI = cast<CallInst>(I);
3270 FunctionType *FTy = CI.getFunctionType();
3271
3272 if (CI.hasOperandBundles())
3273 writeOperandBundles(CI, InstID);
3274
3276
3278
3279 unsigned Flags = getOptimizationFlags(&I);
3281 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3282 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3284 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3285 unsigned(Flags != 0) << bitc::CALL_FMF);
3286 if (Flags != 0)
3287 Vals.push_back(Flags);
3288
3289 Vals.push_back(VE.getTypeID(FTy));
3290 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3291
3292 // Emit value #'s for the fixed parameters.
3293 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3294 // Check for labels (can happen with asm labels).
3295 if (FTy->getParamType(i)->isLabelTy())
3296 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3297 else
3298 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3299 }
3300
3301 // Emit type/value pairs for varargs params.
3302 if (FTy->isVarArg()) {
3303 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3304 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3305 }
3306 break;
3307 }
3308 case Instruction::VAArg:
3310 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3311 pushValue(I.getOperand(0), InstID, Vals); // valist.
3312 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3313 break;
3314 case Instruction::Freeze:
3316 pushValueAndType(I.getOperand(0), InstID, Vals);
3317 break;
3318 }
3319
3320 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3321 Vals.clear();
3322}
3323
3324/// Write a GlobalValue VST to the module. The purpose of this data structure is
3325/// to allow clients to efficiently find the function body.
3326void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3327 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3328 // Get the offset of the VST we are writing, and backpatch it into
3329 // the VST forward declaration record.
3330 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3331 // The BitcodeStartBit was the stream offset of the identification block.
3332 VSTOffset -= bitcodeStartBit();
3333 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3334 // Note that we add 1 here because the offset is relative to one word
3335 // before the start of the identification block, which was historically
3336 // always the start of the regular bitcode header.
3337 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3338
3340
3341 auto Abbv = std::make_shared<BitCodeAbbrev>();
3343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3345 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3346
3347 for (const Function &F : M) {
3348 uint64_t Record[2];
3349
3350 if (F.isDeclaration())
3351 continue;
3352
3353 Record[0] = VE.getValueID(&F);
3354
3355 // Save the word offset of the function (from the start of the
3356 // actual bitcode written to the stream).
3357 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3358 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3359 // Note that we add 1 here because the offset is relative to one word
3360 // before the start of the identification block, which was historically
3361 // always the start of the regular bitcode header.
3362 Record[1] = BitcodeIndex / 32 + 1;
3363
3364 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3365 }
3366
3367 Stream.ExitBlock();
3368}
3369
3370/// Emit names for arguments, instructions and basic blocks in a function.
3371void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3372 const ValueSymbolTable &VST) {
3373 if (VST.empty())
3374 return;
3375
3377
3378 // FIXME: Set up the abbrev, we know how many values there are!
3379 // FIXME: We know if the type names can use 7-bit ascii.
3381
3382 for (const ValueName &Name : VST) {
3383 // Figure out the encoding to use for the name.
3385
3386 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3387 NameVals.push_back(VE.getValueID(Name.getValue()));
3388
3389 // VST_CODE_ENTRY: [valueid, namechar x N]
3390 // VST_CODE_BBENTRY: [bbid, namechar x N]
3391 unsigned Code;
3392 if (isa<BasicBlock>(Name.getValue())) {
3394 if (Bits == SE_Char6)
3395 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3396 } else {
3398 if (Bits == SE_Char6)
3399 AbbrevToUse = VST_ENTRY_6_ABBREV;
3400 else if (Bits == SE_Fixed7)
3401 AbbrevToUse = VST_ENTRY_7_ABBREV;
3402 }
3403
3404 for (const auto P : Name.getKey())
3405 NameVals.push_back((unsigned char)P);
3406
3407 // Emit the finished record.
3408 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3409 NameVals.clear();
3410 }
3411
3412 Stream.ExitBlock();
3413}
3414
3415void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3416 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3417 unsigned Code;
3418 if (isa<BasicBlock>(Order.V))
3420 else
3422
3423 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3424 Record.push_back(VE.getValueID(Order.V));
3425 Stream.EmitRecord(Code, Record);
3426}
3427
3428void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3430 "Expected to be preserving use-list order");
3431
3432 auto hasMore = [&]() {
3433 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3434 };
3435 if (!hasMore())
3436 // Nothing to do.
3437 return;
3438
3440 while (hasMore()) {
3441 writeUseList(std::move(VE.UseListOrders.back()));
3442 VE.UseListOrders.pop_back();
3443 }
3444 Stream.ExitBlock();
3445}
3446
3447/// Emit a function body to the module stream.
3448void ModuleBitcodeWriter::writeFunction(
3449 const Function &F,
3450 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3451 // Save the bitcode index of the start of this function block for recording
3452 // in the VST.
3453 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3454
3457
3459
3460 // Emit the number of basic blocks, so the reader can create them ahead of
3461 // time.
3462 Vals.push_back(VE.getBasicBlocks().size());
3464 Vals.clear();
3465
3466 // If there are function-local constants, emit them now.
3467 unsigned CstStart, CstEnd;
3468 VE.getFunctionConstantRange(CstStart, CstEnd);
3469 writeConstants(CstStart, CstEnd, false);
3470
3471 // If there is function-local metadata, emit it now.
3472 writeFunctionMetadata(F);
3473
3474 // Keep a running idea of what the instruction ID is.
3475 unsigned InstID = CstEnd;
3476
3477 bool NeedsMetadataAttachment = F.hasMetadata();
3478
3479 DILocation *LastDL = nullptr;
3480 SmallSetVector<Function *, 4> BlockAddressUsers;
3481
3482 // Finally, emit all the instructions, in order.
3483 for (const BasicBlock &BB : F) {
3484 for (const Instruction &I : BB) {
3485 writeInstruction(I, InstID, Vals);
3486
3487 if (!I.getType()->isVoidTy())
3488 ++InstID;
3489
3490 // If the instruction has metadata, write a metadata attachment later.
3491 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3492
3493 // If the instruction has a debug location, emit it.
3494 DILocation *DL = I.getDebugLoc();
3495 if (!DL)
3496 continue;
3497
3498 if (DL == LastDL) {
3499 // Just repeat the same debug loc as last time.
3501 continue;
3502 }
3503
3504 Vals.push_back(DL->getLine());
3505 Vals.push_back(DL->getColumn());
3506 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3507 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3508 Vals.push_back(DL->isImplicitCode());
3510 Vals.clear();
3511
3512 LastDL = DL;
3513 }
3514
3515 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3516 SmallVector<Value *> Worklist{BA};
3517 SmallPtrSet<Value *, 8> Visited{BA};
3518 while (!Worklist.empty()) {
3519 Value *V = Worklist.pop_back_val();
3520 for (User *U : V->users()) {
3521 if (auto *I = dyn_cast<Instruction>(U)) {
3522 Function *P = I->getFunction();
3523 if (P != &F)
3524 BlockAddressUsers.insert(P);
3525 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3526 Visited.insert(U).second)
3527 Worklist.push_back(U);
3528 }
3529 }
3530 }
3531 }
3532
3533 if (!BlockAddressUsers.empty()) {
3534 Vals.resize(BlockAddressUsers.size());
3535 for (auto I : llvm::enumerate(BlockAddressUsers))
3536 Vals[I.index()] = VE.getValueID(I.value());
3538 Vals.clear();
3539 }
3540
3541 // Emit names for all the instructions etc.
3542 if (auto *Symtab = F.getValueSymbolTable())
3543 writeFunctionLevelValueSymbolTable(*Symtab);
3544
3545 if (NeedsMetadataAttachment)
3546 writeFunctionMetadataAttachment(F);
3548 writeUseListBlock(&F);
3549 VE.purgeFunction();
3550 Stream.ExitBlock();
3551}
3552
3553// Emit blockinfo, which defines the standard abbreviations etc.
3554void ModuleBitcodeWriter::writeBlockInfo() {
3555 // We only want to emit block info records for blocks that have multiple
3556 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3557 // Other blocks can define their abbrevs inline.
3558 Stream.EnterBlockInfoBlock();
3559
3560 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3561 auto Abbv = std::make_shared<BitCodeAbbrev>();
3567 VST_ENTRY_8_ABBREV)
3568 llvm_unreachable("Unexpected abbrev ordering!");
3569 }
3570
3571 { // 7-bit fixed width VST_CODE_ENTRY strings.
3572 auto Abbv = std::make_shared<BitCodeAbbrev>();
3578 VST_ENTRY_7_ABBREV)
3579 llvm_unreachable("Unexpected abbrev ordering!");
3580 }
3581 { // 6-bit char6 VST_CODE_ENTRY strings.
3582 auto Abbv = std::make_shared<BitCodeAbbrev>();
3588 VST_ENTRY_6_ABBREV)
3589 llvm_unreachable("Unexpected abbrev ordering!");
3590 }
3591 { // 6-bit char6 VST_CODE_BBENTRY strings.
3592 auto Abbv = std::make_shared<BitCodeAbbrev>();
3598 VST_BBENTRY_6_ABBREV)
3599 llvm_unreachable("Unexpected abbrev ordering!");
3600 }
3601
3602 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3603 auto Abbv = std::make_shared<BitCodeAbbrev>();
3608 CONSTANTS_SETTYPE_ABBREV)
3609 llvm_unreachable("Unexpected abbrev ordering!");
3610 }
3611
3612 { // INTEGER abbrev for CONSTANTS_BLOCK.
3613 auto Abbv = std::make_shared<BitCodeAbbrev>();
3617 CONSTANTS_INTEGER_ABBREV)
3618 llvm_unreachable("Unexpected abbrev ordering!");
3619 }
3620
3621 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3622 auto Abbv = std::make_shared<BitCodeAbbrev>();
3624 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3625 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3627 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3628
3630 CONSTANTS_CE_CAST_Abbrev)
3631 llvm_unreachable("Unexpected abbrev ordering!");
3632 }
3633 { // NULL abbrev for CONSTANTS_BLOCK.
3634 auto Abbv = std::make_shared<BitCodeAbbrev>();
3637 CONSTANTS_NULL_Abbrev)
3638 llvm_unreachable("Unexpected abbrev ordering!");
3639 }
3640
3641 // FIXME: This should only use space for first class types!
3642
3643 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3644 auto Abbv = std::make_shared<BitCodeAbbrev>();
3646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3649 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3650 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3651 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3652 FUNCTION_INST_LOAD_ABBREV)
3653 llvm_unreachable("Unexpected abbrev ordering!");
3654 }
3655 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3656 auto Abbv = std::make_shared<BitCodeAbbrev>();
3658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3660 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3661 FUNCTION_INST_UNOP_ABBREV)
3662 llvm_unreachable("Unexpected abbrev ordering!");
3663 }
3664 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3665 auto Abbv = std::make_shared<BitCodeAbbrev>();
3667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3670 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3671 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3672 llvm_unreachable("Unexpected abbrev ordering!");
3673 }
3674 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3675 auto Abbv = std::make_shared<BitCodeAbbrev>();
3677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3680 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3681 FUNCTION_INST_BINOP_ABBREV)
3682 llvm_unreachable("Unexpected abbrev ordering!");
3683 }
3684 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3685 auto Abbv = std::make_shared<BitCodeAbbrev>();
3687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3689 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3691 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3692 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3693 llvm_unreachable("Unexpected abbrev ordering!");
3694 }
3695 { // INST_CAST abbrev for FUNCTION_BLOCK.
3696 auto Abbv = std::make_shared<BitCodeAbbrev>();
3698 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3699 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3701 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3702 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3703 FUNCTION_INST_CAST_ABBREV)
3704 llvm_unreachable("Unexpected abbrev ordering!");
3705 }
3706 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
3707 auto Abbv = std::make_shared<BitCodeAbbrev>();
3709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3714 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3715 FUNCTION_INST_CAST_FLAGS_ABBREV)
3716 llvm_unreachable("Unexpected abbrev ordering!");
3717 }
3718
3719 { // INST_RET abbrev for FUNCTION_BLOCK.
3720 auto Abbv = std::make_shared<BitCodeAbbrev>();
3722 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3723 FUNCTION_INST_RET_VOID_ABBREV)
3724 llvm_unreachable("Unexpected abbrev ordering!");
3725 }
3726 { // INST_RET abbrev for FUNCTION_BLOCK.
3727 auto Abbv = std::make_shared<BitCodeAbbrev>();
3729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3730 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3731 FUNCTION_INST_RET_VAL_ABBREV)
3732 llvm_unreachable("Unexpected abbrev ordering!");
3733 }
3734 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3735 auto Abbv = std::make_shared<BitCodeAbbrev>();
3737 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3738 FUNCTION_INST_UNREACHABLE_ABBREV)
3739 llvm_unreachable("Unexpected abbrev ordering!");
3740 }
3741 {
3742 auto Abbv = std::make_shared<BitCodeAbbrev>();
3745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3746 Log2_32_Ceil(VE.getTypes().size() + 1)));
3749 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3750 FUNCTION_INST_GEP_ABBREV)
3751 llvm_unreachable("Unexpected abbrev ordering!");
3752 }
3753
3754 Stream.ExitBlock();
3755}
3756
3757/// Write the module path strings, currently only used when generating
3758/// a combined index file.
3759void IndexBitcodeWriter::writeModStrings() {
3761
3762 // TODO: See which abbrev sizes we actually need to emit
3763
3764 // 8-bit fixed-width MST_ENTRY strings.
3765 auto Abbv = std::make_shared<BitCodeAbbrev>();
3770 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3771
3772 // 7-bit fixed width MST_ENTRY strings.
3773 Abbv = std::make_shared<BitCodeAbbrev>();
3778 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3779
3780 // 6-bit char6 MST_ENTRY strings.
3781 Abbv = std::make_shared<BitCodeAbbrev>();
3786 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3787
3788 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3789 Abbv = std::make_shared<BitCodeAbbrev>();
3796 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3797
3799 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
3800 StringRef Key = MPSE.getKey();
3801 const auto &Hash = MPSE.getValue();
3803 unsigned AbbrevToUse = Abbrev8Bit;
3804 if (Bits == SE_Char6)
3805 AbbrevToUse = Abbrev6Bit;
3806 else if (Bits == SE_Fixed7)
3807 AbbrevToUse = Abbrev7Bit;
3808
3809 auto ModuleId = ModuleIdMap.size();
3810 ModuleIdMap[Key] = ModuleId;
3811 Vals.push_back(ModuleId);
3812 Vals.append(Key.begin(), Key.end());
3813
3814 // Emit the finished record.
3815 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3816
3817 // Emit an optional hash for the module now
3818 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3819 Vals.assign(Hash.begin(), Hash.end());
3820 // Emit the hash record.
3821 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3822 }
3823
3824 Vals.clear();
3825 });
3826 Stream.ExitBlock();
3827}
3828
3829/// Write the function type metadata related records that need to appear before
3830/// a function summary entry (whether per-module or combined).
3831template <typename Fn>
3833 FunctionSummary *FS,
3834 Fn GetValueID) {
3835 if (!FS->type_tests().empty())
3836 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3837
3839
3840 auto WriteVFuncIdVec = [&](uint64_t Ty,
3842 if (VFs.empty())
3843 return;
3844 Record.clear();
3845 for (auto &VF : VFs) {
3846 Record.push_back(VF.GUID);
3847 Record.push_back(VF.Offset);
3848 }
3849 Stream.EmitRecord(Ty, Record);
3850 };
3851
3852 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3853 FS->type_test_assume_vcalls());
3854 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3855 FS->type_checked_load_vcalls());
3856
3857 auto WriteConstVCallVec = [&](uint64_t Ty,
3859 for (auto &VC : VCs) {
3860 Record.clear();
3861 Record.push_back(VC.VFunc.GUID);
3862 Record.push_back(VC.VFunc.Offset);
3863 llvm::append_range(Record, VC.Args);
3864 Stream.EmitRecord(Ty, Record);
3865 }
3866 };
3867
3868 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3869 FS->type_test_assume_const_vcalls());
3870 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3871 FS->type_checked_load_const_vcalls());
3872
3873 auto WriteRange = [&](ConstantRange Range) {
3874 Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3875 assert(Range.getLower().getNumWords() == 1);
3876 assert(Range.getUpper().getNumWords() == 1);
3877 emitSignedInt64(Record, *Range.getLower().getRawData());
3878 emitSignedInt64(Record, *Range.getUpper().getRawData());
3879 };
3880
3881 if (!FS->paramAccesses().empty()) {
3882 Record.clear();
3883 for (auto &Arg : FS->paramAccesses()) {
3884 size_t UndoSize = Record.size();
3885 Record.push_back(Arg.ParamNo);
3886 WriteRange(Arg.Use);
3887 Record.push_back(Arg.Calls.size());
3888 for (auto &Call : Arg.Calls) {
3889 Record.push_back(Call.ParamNo);
3890 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
3891 if (!ValueID) {
3892 // If ValueID is unknown we can't drop just this call, we must drop
3893 // entire parameter.
3894 Record.resize(UndoSize);
3895 break;
3896 }
3897 Record.push_back(*ValueID);
3898 WriteRange(Call.Offsets);
3899 }
3900 }
3901 if (!Record.empty())
3903 }
3904}
3905
3906/// Collect type IDs from type tests used by function.
3907static void
3909 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3910 if (!FS->type_tests().empty())
3911 for (auto &TT : FS->type_tests())
3912 ReferencedTypeIds.insert(TT);
3913
3914 auto GetReferencedTypesFromVFuncIdVec =
3916 for (auto &VF : VFs)
3917 ReferencedTypeIds.insert(VF.GUID);
3918 };
3919
3920 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3921 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3922
3923 auto GetReferencedTypesFromConstVCallVec =
3925 for (auto &VC : VCs)
3926 ReferencedTypeIds.insert(VC.VFunc.GUID);
3927 };
3928
3929 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3930 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3931}
3932
3934 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3936 NameVals.push_back(args.size());
3937 llvm::append_range(NameVals, args);
3938
3939 NameVals.push_back(ByArg.TheKind);
3940 NameVals.push_back(ByArg.Info);
3941 NameVals.push_back(ByArg.Byte);
3942 NameVals.push_back(ByArg.Bit);
3943}
3944
3946 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3947 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3948 NameVals.push_back(Id);
3949
3950 NameVals.push_back(Wpd.TheKind);
3951 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3952 NameVals.push_back(Wpd.SingleImplName.size());
3953
3954 NameVals.push_back(Wpd.ResByArg.size());
3955 for (auto &A : Wpd.ResByArg)
3956 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3957}
3958
3960 StringTableBuilder &StrtabBuilder,
3961 const std::string &Id,
3962 const TypeIdSummary &Summary) {
3963 NameVals.push_back(StrtabBuilder.add(Id));
3964 NameVals.push_back(Id.size());
3965
3966 NameVals.push_back(Summary.TTRes.TheKind);
3967 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3968 NameVals.push_back(Summary.TTRes.AlignLog2);
3969 NameVals.push_back(Summary.TTRes.SizeM1);
3970 NameVals.push_back(Summary.TTRes.BitMask);
3971 NameVals.push_back(Summary.TTRes.InlineBits);
3972
3973 for (auto &W : Summary.WPDRes)
3974 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3975 W.second);
3976}
3977
3979 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3980 const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3981 ValueEnumerator &VE) {
3982 NameVals.push_back(StrtabBuilder.add(Id));
3983 NameVals.push_back(Id.size());
3984
3985 for (auto &P : Summary) {
3986 NameVals.push_back(P.AddressPointOffset);
3987 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3988 }
3989}
3990
3992 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
3993 unsigned AllocAbbrev, bool PerModule,
3994 std::function<unsigned(const ValueInfo &VI)> GetValueID,
3995 std::function<unsigned(unsigned)> GetStackIndex) {
3997
3998 for (auto &CI : FS->callsites()) {
3999 Record.clear();
4000 // Per module callsite clones should always have a single entry of
4001 // value 0.
4002 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4003 Record.push_back(GetValueID(CI.Callee));
4004 if (!PerModule) {
4005 Record.push_back(CI.StackIdIndices.size());
4006 Record.push_back(CI.Clones.size());
4007 }
4008 for (auto Id : CI.StackIdIndices)
4009 Record.push_back(GetStackIndex(Id));
4010 if (!PerModule) {
4011 for (auto V : CI.Clones)
4012 Record.push_back(V);
4013 }
4016 Record, CallsiteAbbrev);
4017 }
4018
4019 for (auto &AI : FS->allocs()) {
4020 Record.clear();
4021 // Per module alloc versions should always have a single entry of
4022 // value 0.
4023 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4024 if (!PerModule) {
4025 Record.push_back(AI.MIBs.size());
4026 Record.push_back(AI.Versions.size());
4027 }
4028 for (auto &MIB : AI.MIBs) {
4029 Record.push_back((uint8_t)MIB.AllocType);
4030 Record.push_back(MIB.StackIdIndices.size());
4031 for (auto Id : MIB.StackIdIndices)
4032 Record.push_back(GetStackIndex(Id));
4033 }
4034 if (!PerModule) {
4035 for (auto V : AI.Versions)
4036 Record.push_back(V);
4037 }
4038 Stream.EmitRecord(PerModule ? bitc::FS_PERMODULE_ALLOC_INFO
4040 Record, AllocAbbrev);
4041 }
4042}
4043
4044// Helper to emit a single function summary record.
4045void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4047 unsigned ValueID, unsigned FSCallsRelBFAbbrev,
4048 unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4049 unsigned AllocAbbrev, const Function &F) {
4050 NameVals.push_back(ValueID);
4051
4052 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4053
4055 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4056 return {VE.getValueID(VI.getValue())};
4057 });
4058
4060 Stream, FS, CallsiteAbbrev, AllocAbbrev,
4061 /*PerModule*/ true,
4062 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4063 /*GetStackIndex*/ [&](unsigned I) { return I; });
4064
4065 auto SpecialRefCnts = FS->specialRefCounts();
4066 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4067 NameVals.push_back(FS->instCount());
4068 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4069 NameVals.push_back(FS->refs().size());
4070 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4071 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4072
4073 for (auto &RI : FS->refs())
4074 NameVals.push_back(VE.getValueID(RI.getValue()));
4075
4076 const bool UseRelBFRecord =
4077 WriteRelBFToSummary && !F.hasProfileData() &&
4079 for (auto &ECI : FS->calls()) {
4080 NameVals.push_back(getValueId(ECI.first));
4081 if (UseRelBFRecord)
4082 NameVals.push_back(getEncodedRelBFCallEdgeInfo(ECI.second));
4083 else
4084 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4085 }
4086
4087 unsigned FSAbbrev =
4088 (UseRelBFRecord ? FSCallsRelBFAbbrev : FSCallsProfileAbbrev);
4089 unsigned Code =
4091
4092 // Emit the finished record.
4093 Stream.EmitRecord(Code, NameVals, FSAbbrev);
4094 NameVals.clear();
4095}
4096
4097// Collect the global value references in the given variable's initializer,
4098// and emit them in a summary record.
4099void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4100 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4101 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4102 auto VI = Index->getValueInfo(V.getGUID());
4103 if (!VI || VI.getSummaryList().empty()) {
4104 // Only declarations should not have a summary (a declaration might however
4105 // have a summary if the def was in module level asm).
4106 assert(V.isDeclaration());
4107 return;
4108 }
4109 auto *Summary = VI.getSummaryList()[0].get();
4110 NameVals.push_back(VE.getValueID(&V));
4111 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4112 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4113 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4114
4115 auto VTableFuncs = VS->vTableFuncs();
4116 if (!VTableFuncs.empty())
4117 NameVals.push_back(VS->refs().size());
4118
4119 unsigned SizeBeforeRefs = NameVals.size();
4120 for (auto &RI : VS->refs())
4121 NameVals.push_back(VE.getValueID(RI.getValue()));
4122 // Sort the refs for determinism output, the vector returned by FS->refs() has
4123 // been initialized from a DenseSet.
4124 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4125
4126 if (VTableFuncs.empty())
4128 FSModRefsAbbrev);
4129 else {
4130 // VTableFuncs pairs should already be sorted by offset.
4131 for (auto &P : VTableFuncs) {
4132 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4133 NameVals.push_back(P.VTableOffset);
4134 }
4135
4137 FSModVTableRefsAbbrev);
4138 }
4139 NameVals.clear();
4140}
4141
4142/// Emit the per-module summary section alongside the rest of
4143/// the module's bitcode.
4144void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4145 // By default we compile with ThinLTO if the module has a summary, but the
4146 // client can request full LTO with a module flag.
4147 bool IsThinLTO = true;
4148 if (auto *MD =
4149 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4150 IsThinLTO = MD->getZExtValue();
4153 4);
4154
4155 Stream.EmitRecord(
4158
4159 // Write the index flags.
4160 uint64_t Flags = 0;
4161 // Bits 1-3 are set only in the combined index, skip them.
4162 if (Index->enableSplitLTOUnit())
4163 Flags |= 0x8;
4164 if (Index->hasUnifiedLTO())
4165 Flags |= 0x200;
4166
4168
4169 if (Index->begin() == Index->end()) {
4170 Stream.ExitBlock();
4171 return;
4172 }
4173
4174 for (const auto &GVI : valueIds()) {
4176 ArrayRef<uint64_t>{GVI.second, GVI.first});
4177 }
4178
4179 if (!Index->stackIds().empty()) {
4180 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4181 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4182 // numids x stackid
4183 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4184 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4185 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4186 Stream.EmitRecord(bitc::FS_STACK_IDS, Index->stackIds(), StackIdAbbvId);
4187 }
4188
4189 // Abbrev for FS_PERMODULE_PROFILE.
4190 auto Abbv = std::make_shared<BitCodeAbbrev>();
4192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4193 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4195 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4196 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4197 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4198 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4199 // numrefs x valueid, n x (valueid, hotness+tailcall flags)
4202 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4203
4204 // Abbrev for FS_PERMODULE_RELBF.
4205 Abbv = std::make_shared<BitCodeAbbrev>();
4207 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4214 // numrefs x valueid, n x (valueid, rel_block_freq+tailcall])
4217 unsigned FSCallsRelBFAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4218
4219 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4220 Abbv = std::make_shared<BitCodeAbbrev>();
4222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4226 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4227
4228 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4229 Abbv = std::make_shared<BitCodeAbbrev>();
4231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4234 // numrefs x valueid, n x (valueid , offset)
4237 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4238
4239 // Abbrev for FS_ALIAS.
4240 Abbv = std::make_shared<BitCodeAbbrev>();
4241 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4245 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4246
4247 // Abbrev for FS_TYPE_ID_METADATA
4248 Abbv = std::make_shared<BitCodeAbbrev>();
4250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4252 // n x (valueid , offset)
4255 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4256
4257 Abbv = std::make_shared<BitCodeAbbrev>();
4259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4260 // n x stackidindex
4263 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4264
4265 Abbv = std::make_shared<BitCodeAbbrev>();
4267 // n x (alloc type, numstackids, numstackids x stackidindex)
4270 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4271
4273 // Iterate over the list of functions instead of the Index to
4274 // ensure the ordering is stable.
4275 for (const Function &F : M) {
4276 // Summary emission does not support anonymous functions, they have to
4277 // renamed using the anonymous function renaming pass.
4278 if (!F.hasName())
4279 report_fatal_error("Unexpected anonymous function when writing summary");
4280
4281 ValueInfo VI = Index->getValueInfo(F.getGUID());
4282 if (!VI || VI.getSummaryList().empty()) {
4283 // Only declarations should not have a summary (a declaration might
4284 // however have a summary if the def was in module level asm).
4285 assert(F.isDeclaration());
4286 continue;
4287 }
4288 auto *Summary = VI.getSummaryList()[0].get();
4289 writePerModuleFunctionSummaryRecord(
4290 NameVals, Summary, VE.getValueID(&F), FSCallsRelBFAbbrev,
4291 FSCallsProfileAbbrev, CallsiteAbbrev, AllocAbbrev, F);
4292 }
4293
4294 // Capture references from GlobalVariable initializers, which are outside
4295 // of a function scope.
4296 for (const GlobalVariable &G : M.globals())
4297 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4298 FSModVTableRefsAbbrev);
4299
4300 for (const GlobalAlias &A : M.aliases()) {
4301 auto *Aliasee = A.getAliaseeObject();
4302 // Skip ifunc and nameless functions which don't have an entry in the
4303 // summary.
4304 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4305 continue;
4306 auto AliasId = VE.getValueID(&A);
4307 auto AliaseeId = VE.getValueID(Aliasee);
4308 NameVals.push_back(AliasId);
4309 auto *Summary = Index->getGlobalValueSummary(A);
4310 AliasSummary *AS = cast<AliasSummary>(Summary);
4311 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4312 NameVals.push_back(AliaseeId);
4313 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4314 NameVals.clear();
4315 }
4316
4317 for (auto &S : Index->typeIdCompatibleVtableMap()) {
4318 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4319 S.second, VE);
4320 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4321 TypeIdCompatibleVtableAbbrev);
4322 NameVals.clear();
4323 }
4324
4325 if (Index->getBlockCount())
4327 ArrayRef<uint64_t>{Index->getBlockCount()});
4328
4329 Stream.ExitBlock();
4330}
4331
4332/// Emit the combined summary section into the combined index file.
4333void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4335 Stream.EmitRecord(
4338
4339 // Write the index flags.
4341
4342 for (const auto &GVI : valueIds()) {
4344 ArrayRef<uint64_t>{GVI.second, GVI.first});
4345 }
4346
4347 if (!StackIdIndices.empty()) {
4348 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4349 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4350 // numids x stackid
4351 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4352 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4353 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4354 // Write the stack ids used by this index, which will be a subset of those in
4355 // the full index in the case of distributed indexes.
4356 std::vector<uint64_t> StackIds;
4357 for (auto &I : StackIdIndices)
4358 StackIds.push_back(Index.getStackIdAtIndex(I));
4359 Stream.EmitRecord(bitc::FS_STACK_IDS, StackIds, StackIdAbbvId);
4360 }
4361
4362 // Abbrev for FS_COMBINED_PROFILE.
4363 auto Abbv = std::make_shared<BitCodeAbbrev>();
4365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4370 Abbv->Add(BitCodeAbbrevOp(