LLVM 24.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"
33#include "llvm/Config/llvm-config.h"
34#include "llvm/IR/Attributes.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/Comdat.h"
37#include "llvm/IR/Constant.h"
39#include "llvm/IR/Constants.h"
41#include "llvm/IR/DebugLoc.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalIFunc.h"
47#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/InlineAsm.h"
50#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Metadata.h"
55#include "llvm/IR/Module.h"
57#include "llvm/IR/Operator.h"
58#include "llvm/IR/Type.h"
60#include "llvm/IR/Value.h"
71#include "llvm/Support/Endian.h"
72#include "llvm/Support/Error.h"
75#include "llvm/Support/SHA1.h"
78#include <algorithm>
79#include <cassert>
80#include <cstddef>
81#include <cstdint>
82#include <iterator>
83#include <map>
84#include <memory>
85#include <optional>
86#include <string>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91using namespace llvm::memprof;
92
94 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
95 cl::desc("Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
98 "bitcode-flush-threshold", cl::Hidden, cl::init(512),
99 cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
100
101// Since we only use the context information in the memprof summary records in
102// the LTO backends to do assertion checking, save time and space by only
103// serializing the context for non-NDEBUG builds.
104// TODO: Currently this controls writing context of the allocation info records,
105// which are larger and more expensive, but we should do this for the callsite
106// records as well.
107// FIXME: Convert to a const once this has undergone more sigificant testing.
108static cl::opt<bool>
109 CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden,
110#ifdef NDEBUG
111 cl::init(false),
112#else
113 cl::init(true),
114#endif
115 cl::desc(""));
116
118 "preserve-bc-uselistorder", cl::Hidden, cl::init(true),
119 cl::desc("Preserve use-list order when writing LLVM bitcode."));
120
121namespace {
122
123/// These are manifest constants used by the bitcode writer. They do not need to
124/// be kept in sync with the reader, but need to be consistent within this file.
125enum {
126 // VALUE_SYMTAB_BLOCK abbrev id's.
127 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
128 VST_ENTRY_7_ABBREV,
129 VST_ENTRY_6_ABBREV,
130 VST_BBENTRY_6_ABBREV,
131
132 // CONSTANTS_BLOCK abbrev id's.
133 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
134 CONSTANTS_INTEGER_ABBREV,
135 CONSTANTS_BYTE_ABBREV,
136 CONSTANTS_CE_CAST_Abbrev,
137 CONSTANTS_NULL_Abbrev,
138
139 // FUNCTION_BLOCK abbrev id's.
140 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
141 FUNCTION_INST_STORE_ABBREV,
142 FUNCTION_INST_UNOP_ABBREV,
143 FUNCTION_INST_UNOP_FLAGS_ABBREV,
144 FUNCTION_INST_BINOP_ABBREV,
145 FUNCTION_INST_BINOP_FLAGS_ABBREV,
146 FUNCTION_INST_CAST_ABBREV,
147 FUNCTION_INST_CAST_FLAGS_ABBREV,
148 FUNCTION_INST_RET_VOID_ABBREV,
149 FUNCTION_INST_RET_VAL_ABBREV,
150 FUNCTION_INST_BR_UNCOND_ABBREV,
151 FUNCTION_INST_BR_COND_ABBREV,
152 FUNCTION_INST_UNREACHABLE_ABBREV,
153 FUNCTION_INST_GEP_ABBREV,
154 FUNCTION_INST_CMP_ABBREV,
155 FUNCTION_INST_CMP_FLAGS_ABBREV,
156 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
157 FUNCTION_DEBUG_LOC_ABBREV,
158 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
159};
160
161/// Abstract class to manage the bitcode writing, subclassed for each bitcode
162/// file type.
163class BitcodeWriterBase {
164protected:
165 /// The stream created and owned by the client.
166 BitstreamWriter &Stream;
167
168 StringTableBuilder &StrtabBuilder;
169
170public:
171 /// Constructs a BitcodeWriterBase object that writes to the provided
172 /// \p Stream.
173 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
174 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
175
176protected:
177 void writeModuleVersion();
178};
179
180void BitcodeWriterBase::writeModuleVersion() {
181 // VERSION: [version#]
182 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
183}
184
185/// Base class to manage the module bitcode writing, currently subclassed for
186/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
187class ModuleBitcodeWriterBase : public BitcodeWriterBase {
188protected:
189 /// The Module to write to bitcode.
190 const Module &M;
191
192 /// Enumerates ids for all values in the module.
193 ValueEnumerator VE;
194
195 /// Optional per-module index to write for ThinLTO.
196 const ModuleSummaryIndex *Index;
197
198 /// Map that holds the correspondence between GUIDs in the summary index,
199 /// that came from indirect call profiles, and a value id generated by this
200 /// class to use in the VST and summary block records.
201 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
202
203 /// Tracks the last value id recorded in the GUIDToValueMap.
204 unsigned GlobalValueId;
205
206 /// Saves the offset of the VSTOffset record that must eventually be
207 /// backpatched with the offset of the actual VST.
208 uint64_t VSTOffsetPlaceholder = 0;
209
210public:
211 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
212 /// writing to the provided \p Buffer.
213 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
214 BitstreamWriter &Stream,
215 bool ShouldPreserveUseListOrder,
216 const ModuleSummaryIndex *Index)
217 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
218 VE(M, PreserveBitcodeUseListOrder.getNumOccurrences()
220 : ShouldPreserveUseListOrder),
221 Index(Index) {
222 // Assign ValueIds to any callee values in the index that came from
223 // indirect call profiles and were recorded as a GUID not a Value*
224 // (which would have been assigned an ID by the ValueEnumerator).
225 // The starting ValueId is just after the number of values in the
226 // ValueEnumerator, so that they can be emitted in the VST.
227 GlobalValueId = VE.getValues().size();
228 if (!Index)
229 return;
230 // Sort by GUID for deterministic value ID assignment.
231 for (const auto &GUIDSummaryLists :
232 Index->sortedGlobalValueSummariesRange())
233 // Examine all summaries for this GUID.
234 for (auto &Summary : GUIDSummaryLists.second.getSummaryList())
235 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) {
236 // For each call in the function summary, see if the call
237 // is to a GUID (which means it is for an indirect call,
238 // otherwise we would have a Value for it). If so, synthesize
239 // a value id.
240 for (auto &CallEdge : FS->calls())
241 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
242 assignValueId(CallEdge.first.getGUID());
243
244 // For each referenced variables in the function summary, see if the
245 // variable is represented by a GUID (as opposed to a symbol to
246 // declarations or definitions in the module). If so, synthesize a
247 // value id.
248 for (auto &RefEdge : FS->refs())
249 if (!RefEdge.haveGVs() || !RefEdge.getValue())
250 assignValueId(RefEdge.getGUID());
251 }
252 }
253
254protected:
255 void writePerModuleGlobalValueSummary();
256 void writeGUIDList();
257
258private:
259 void writePerModuleFunctionSummaryRecord(
260 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
261 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
262 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
263 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
264 CallStackId &CallStackCount);
265 void writeModuleLevelReferences(const GlobalVariable &V,
266 SmallVector<uint64_t, 64> &NameVals,
267 unsigned FSModRefsAbbrev,
268 unsigned FSModVTableRefsAbbrev);
269
270 void assignValueId(GlobalValue::GUID ValGUID) {
271 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
272 }
273
274 unsigned getValueId(GlobalValue::GUID ValGUID) {
275 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
276 // Expect that any GUID value had a value Id assigned by an
277 // earlier call to assignValueId.
278 assert(VMI != GUIDToValueIdMap.end() &&
279 "GUID does not have assigned value Id");
280 return VMI->second;
281 }
282
283 // Helper to get the valueId for the type of value recorded in VI.
284 unsigned getValueId(ValueInfo VI) {
285 if (!VI.haveGVs() || !VI.getValue())
286 return getValueId(VI.getGUID());
287 return VE.getValueID(VI.getValue());
288 }
289
290 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
291};
292
293/// Class to manage the bitcode writing for a module.
294class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
295 /// True if a module hash record should be written.
296 bool GenerateHash;
297
298 /// If non-null, when GenerateHash is true, the resulting hash is written
299 /// into ModHash.
300 ModuleHash *ModHash;
301
302 SHA1 Hasher;
303
304 /// The start bit of the identification block.
305 uint64_t BitcodeStartBit;
306
307 /// Abbrev for DILocations that carry an irlayers operand. Locations without
308 /// layers use the shorter abbrev threaded through writeDILocation's \p
309 /// Abbrev parameter, so they pay nothing for a field they do not use.
310 unsigned DILocationLayersAbbrev = 0;
311
312public:
313 /// Constructs a ModuleBitcodeWriter object for the given Module,
314 /// writing to the provided \p Buffer.
315 ModuleBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
316 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
317 const ModuleSummaryIndex *Index, bool GenerateHash,
318 ModuleHash *ModHash = nullptr)
319 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
320 ShouldPreserveUseListOrder, Index),
321 GenerateHash(GenerateHash), ModHash(ModHash),
322 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
323
324 /// Emit the current module to the bitstream.
325 void write();
326
327private:
328 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
329
330 size_t addToStrtab(StringRef Str);
331
332 void writeAttributeGroupTable();
333 void writeAttributeTable();
334 void writeTypeTable();
335 void writeComdats();
336 void writeValueSymbolTableForwardDecl();
337 void writeModuleInfo();
338 void writeValueAsMetadata(const ValueAsMetadata *MD,
339 SmallVectorImpl<uint64_t> &Record);
340 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
341 unsigned Abbrev);
342 unsigned createDILocationAbbrev(bool WithIRLayers);
343 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
344 unsigned &Abbrev);
345 void writeDILayerLoc(const DILayerLoc *N, SmallVectorImpl<uint64_t> &Record,
346 unsigned Abbrev);
347 void writeDILayerLocList(const DILayerLocList *N,
348 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
349 unsigned createGenericDINodeAbbrev();
350 void writeGenericDINode(const GenericDINode *N,
351 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
352 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
353 unsigned Abbrev);
354 void writeDIGenericSubrange(const DIGenericSubrange *N,
355 SmallVectorImpl<uint64_t> &Record,
356 unsigned Abbrev);
357 void writeDIEnumerator(const DIEnumerator *N,
358 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
359 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
360 unsigned Abbrev);
361 void writeDIFixedPointType(const DIFixedPointType *N,
362 SmallVectorImpl<uint64_t> &Record,
363 unsigned Abbrev);
364 void writeDIStringType(const DIStringType *N,
365 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
366 void writeDIDerivedType(const DIDerivedType *N,
367 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
368 void writeDISubrangeType(const DISubrangeType *N,
369 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
370 void writeDICompositeType(const DICompositeType *N,
371 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
372 void writeDISubroutineType(const DISubroutineType *N,
373 SmallVectorImpl<uint64_t> &Record,
374 unsigned Abbrev);
375 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
376 unsigned Abbrev);
377 void writeDICompileUnit(const DICompileUnit *N,
378 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
379 void writeDISubprogram(const DISubprogram *N,
380 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
381 void writeDILexicalBlock(const DILexicalBlock *N,
382 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
383 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
384 SmallVectorImpl<uint64_t> &Record,
385 unsigned Abbrev);
386 void writeDICommonBlock(const DICommonBlock *N,
387 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
388 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
389 unsigned Abbrev);
390 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
391 unsigned Abbrev);
392 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
393 unsigned Abbrev);
394 void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record);
395 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
396 unsigned Abbrev);
397 void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
398 unsigned Abbrev);
399 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
400 SmallVectorImpl<uint64_t> &Record,
401 unsigned Abbrev);
402 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
403 SmallVectorImpl<uint64_t> &Record,
404 unsigned Abbrev);
405 void writeDIGlobalVariable(const DIGlobalVariable *N,
406 SmallVectorImpl<uint64_t> &Record,
407 unsigned Abbrev);
408 void writeDILocalVariable(const DILocalVariable *N,
409 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
410 void writeDILabel(const DILabel *N,
411 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
412 void writeDIExpression(const DIExpression *N,
413 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
414 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
415 SmallVectorImpl<uint64_t> &Record,
416 unsigned Abbrev);
417 void writeDIObjCProperty(const DIObjCProperty *N,
418 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
419 void writeDIProperty(const DIProperty *N, SmallVectorImpl<uint64_t> &Record,
420 unsigned Abbrev);
421 void writeDIImportedEntity(const DIImportedEntity *N,
422 SmallVectorImpl<uint64_t> &Record,
423 unsigned Abbrev);
424 unsigned createNamedMetadataAbbrev();
425 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
426 unsigned createMetadataStringsAbbrev();
427 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
428 SmallVectorImpl<uint64_t> &Record);
429 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
430 SmallVectorImpl<uint64_t> &Record,
431 std::vector<unsigned> *MDAbbrevs = nullptr,
432 std::vector<uint64_t> *IndexPos = nullptr);
433 void writeModuleMetadata();
434 void writeFunctionMetadata(const Function &F);
435 void writeFunctionMetadataAttachment(const Function &F);
436 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
437 const GlobalObject &GO);
438 void writeModuleMetadataKinds();
439 void writeOperandBundleTags();
440 void writeSyncScopeNames();
441 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
442 void writeModuleConstants();
443 bool pushValueAndType(const Value *V, unsigned InstID,
444 SmallVectorImpl<unsigned> &Vals);
445 bool pushValueOrMetadata(const Value *V, unsigned InstID,
446 SmallVectorImpl<unsigned> &Vals);
447 void writeOperandBundles(const CallBase &CB, unsigned InstID);
448 void pushValue(const Value *V, unsigned InstID,
449 SmallVectorImpl<unsigned> &Vals);
450 void pushValueSigned(const Value *V, unsigned InstID,
451 SmallVectorImpl<uint64_t> &Vals);
452 void writeInstruction(const Instruction &I, unsigned InstID,
453 SmallVectorImpl<unsigned> &Vals);
454 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
455 void writeGlobalValueSymbolTable(
456 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
457 void writeUseList(UseListOrder &&Order);
458 void writeUseListBlock(const Function *F);
459 void
460 writeFunction(const Function &F,
461 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
462 void writeBlockInfo();
463 void writeModuleHash(StringRef View);
464
465 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
466 return unsigned(SSID);
467 }
468
469 unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
470};
471
472/// Class to manage the bitcode writing for a combined index.
473class IndexBitcodeWriter : public BitcodeWriterBase {
474 /// The combined index to write to bitcode.
475 const ModuleSummaryIndex &Index;
476
477 /// When writing combined summaries, provides the set of global value
478 /// summaries for which the value (function, function alias, etc) should be
479 /// imported as a declaration.
480 const GVSummaryPtrSet *DecSummaries = nullptr;
481
482 /// When writing a subset of the index for distributed backends, client
483 /// provides a map of modules to the corresponding GUIDs/summaries to write.
484 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex;
485
486 /// The summaries in ModuleToSummariesForIndex, sorted by GUID. The
487 /// per-module maps are DenseMaps whose iteration order depends on insertion
488 /// order, which can change with unrelated modules in the link. Writing in
489 /// this order makes logically identical indexes byte-identical.
491 SortedSummariesForIndex;
492
493 /// Map that holds the correspondence between the GUID used in the combined
494 /// index and a value id generated by this class to use in references.
495 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
496
497 // The stack ids used by this index, which will be a subset of those in
498 // the full index in the case of distributed indexes.
499 std::vector<uint64_t> StackIds;
500
501 // Keep a map of the stack id indices used by records being written for this
502 // index to the index of the corresponding stack id in the above StackIds
503 // vector. Ensures we write each referenced stack id once.
504 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
505
506 /// Tracks the last value id recorded in the GUIDToValueMap.
507 unsigned GlobalValueId = 0;
508
509 /// Tracks the assignment of module paths in the module path string table to
510 /// an id assigned for use in summary references to the module path.
511 DenseMap<StringRef, uint64_t> ModuleIdMap;
512
513public:
514 /// Constructs a IndexBitcodeWriter object for the given combined index,
515 /// writing to the provided \p Buffer. When writing a subset of the index
516 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
517 /// If provided, \p DecSummaries specifies the set of summaries for which
518 /// the corresponding functions or aliased functions should be imported as a
519 /// declaration (but not definition) for each module.
520 IndexBitcodeWriter(
521 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
522 const ModuleSummaryIndex &Index,
523 const GVSummaryPtrSet *DecSummaries = nullptr,
524 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex = nullptr)
525 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
526 DecSummaries(DecSummaries),
527 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
528 if (ModuleToSummariesForIndex) {
529 for (const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
530 llvm::append_range(SortedSummariesForIndex, Summaries);
531 // Each module's summaries are in DenseMap order, which depends on
532 // insertion order. Sort by GUID for byte-identical output. A GUID may
533 // appear under more than one module; the stable sort keeps those in the
534 // std::map's module path order.
535 llvm::stable_sort(SortedSummariesForIndex, llvm::less_first());
536 }
537
538 // See if the StackIdIndex was already added to the StackId map and
539 // vector. If not, record it.
540 auto RecordStackIdReference = [&](unsigned StackIdIndex) {
541 // If the StackIdIndex is not yet in the map, the below insert ensures
542 // that it will point to the new StackIds vector entry we push to just
543 // below.
544 auto Inserted =
545 StackIdIndicesToIndex.insert({StackIdIndex, StackIds.size()});
546 if (Inserted.second)
547 StackIds.push_back(Index.getStackIdAtIndex(StackIdIndex));
548 };
549
550 // Assign unique value ids to all summaries to be written, for use
551 // in writing out the call graph edges. Save the mapping from GUID
552 // to the new global value id to use when writing those edges, which
553 // are currently saved in the index in terms of GUID.
554 forEachSummary([&](GVInfo I, bool IsAliasee) {
555 GUIDToValueIdMap[I.first] = ++GlobalValueId;
556 // If this is invoked for an aliasee, we want to record the above mapping,
557 // but not the information needed for its summary entry (if the aliasee is
558 // to be imported, we will invoke this separately with IsAliasee=false).
559 if (IsAliasee)
560 return;
561 auto *FS = dyn_cast<FunctionSummary>(I.second);
562 if (!FS)
563 return;
564 // Record all stack id indices actually used in the summary entries being
565 // written, so that we can compact them in the case of distributed ThinLTO
566 // indexes.
567 for (auto &CI : FS->callsites()) {
568 // If the stack id list is empty, this callsite info was synthesized for
569 // a missing tail call frame. Ensure that the callee's GUID gets a value
570 // id. Normally we only generate these for defined summaries, which in
571 // the case of distributed ThinLTO is only the functions already defined
572 // in the module or that we want to import. We don't bother to include
573 // all the callee symbols as they aren't normally needed in the backend.
574 // However, for the synthesized callsite infos we do need the callee
575 // GUID in the backend so that we can correlate the identified callee
576 // with this callsite info (which for non-tail calls is done by the
577 // ordering of the callsite infos and verified via stack ids).
578 if (CI.StackIdIndices.empty()) {
579 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
580 continue;
581 }
582 for (auto Idx : CI.StackIdIndices)
583 RecordStackIdReference(Idx);
584 }
586 for (auto &AI : FS->allocs())
587 for (auto &MIB : AI.MIBs)
588 for (auto Idx : MIB.StackIdIndices)
589 RecordStackIdReference(Idx);
590 }
591 });
592 }
593
594 /// The below iterator returns the GUID and associated summary.
595 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
596
597 /// Calls the callback for each value GUID and summary to be written to
598 /// bitcode. This hides the details of whether they are being pulled from the
599 /// entire index or just those in a provided ModuleToSummariesForIndex map.
600 template<typename Functor>
601 void forEachSummary(Functor Callback) {
602 if (ModuleToSummariesForIndex) {
603 for (auto &[GUID, GVS] : SortedSummariesForIndex) {
604 Callback({GUID, GVS}, false);
605 // Ensure aliasee is handled, e.g. for assigning a valueId,
606 // even if we are not importing the aliasee directly (the
607 // imported alias will contain a copy of aliasee).
608 if (auto *AS = dyn_cast<AliasSummary>(GVS))
609 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
610 }
611 } else {
612 // Sort by GUID for deterministic output.
613 for (const auto &Summaries : Index.sortedGlobalValueSummariesRange())
614 for (auto &Summary : Summaries.second.getSummaryList())
615 Callback({Summaries.first, Summary.get()}, false);
616 }
617 }
618
619 /// Calls the callback for each entry in the modulePaths StringMap that
620 /// should be written to the module path string table. This hides the details
621 /// of whether they are being pulled from the entire index or just those in a
622 /// provided ModuleToSummariesForIndex map.
623 template <typename Functor> void forEachModule(Functor Callback) {
624 if (ModuleToSummariesForIndex) {
625 for (const auto &M : *ModuleToSummariesForIndex) {
626 const auto &MPI = Index.modulePaths().find(M.first);
627 if (MPI == Index.modulePaths().end()) {
628 // This should only happen if the bitcode file was empty, in which
629 // case we shouldn't be importing (the ModuleToSummariesForIndex
630 // would only include the module we are writing and index for).
631 assert(ModuleToSummariesForIndex->size() == 1);
632 continue;
633 }
634 Callback(*MPI);
635 }
636 } else {
637 // Since StringMap iteration order isn't guaranteed, order by path string
638 // first.
639 // FIXME: Make this a vector of StringMapEntry instead to avoid the later
640 // map lookup.
641 std::vector<StringRef> ModulePaths;
642 for (auto &[ModPath, _] : Index.modulePaths())
643 ModulePaths.push_back(ModPath);
644 llvm::sort(ModulePaths);
645 for (auto &ModPath : ModulePaths)
646 Callback(*Index.modulePaths().find(ModPath));
647 }
648 }
649
650 /// Main entry point for writing a combined index to bitcode.
651 void write();
652
653private:
654 void writeModStrings();
655 void writeCombinedGlobalValueSummary();
656
657 std::optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
658 auto VMI = GUIDToValueIdMap.find(ValGUID);
659 if (VMI == GUIDToValueIdMap.end())
660 return std::nullopt;
661 return VMI->second;
662 }
663
664 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
665};
666
667} // end anonymous namespace
668
669static unsigned getEncodedCastOpcode(unsigned Opcode) {
670 switch (Opcode) {
671 default: llvm_unreachable("Unknown cast instruction!");
672 case Instruction::Trunc : return bitc::CAST_TRUNC;
673 case Instruction::ZExt : return bitc::CAST_ZEXT;
674 case Instruction::SExt : return bitc::CAST_SEXT;
675 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
676 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
677 case Instruction::UIToFP : return bitc::CAST_UITOFP;
678 case Instruction::SIToFP : return bitc::CAST_SITOFP;
679 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
680 case Instruction::FPExt : return bitc::CAST_FPEXT;
681 case Instruction::PtrToAddr: return bitc::CAST_PTRTOADDR;
682 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
683 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
684 case Instruction::BitCast : return bitc::CAST_BITCAST;
685 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
686 }
687}
688
689static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
690 switch (Opcode) {
691 default: llvm_unreachable("Unknown binary instruction!");
692 case Instruction::FNeg: return bitc::UNOP_FNEG;
693 }
694}
695
696static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
697 switch (Opcode) {
698 default: llvm_unreachable("Unknown binary instruction!");
699 case Instruction::Add:
700 case Instruction::FAdd: return bitc::BINOP_ADD;
701 case Instruction::Sub:
702 case Instruction::FSub: return bitc::BINOP_SUB;
703 case Instruction::Mul:
704 case Instruction::FMul: return bitc::BINOP_MUL;
705 case Instruction::UDiv: return bitc::BINOP_UDIV;
706 case Instruction::FDiv:
707 case Instruction::SDiv: return bitc::BINOP_SDIV;
708 case Instruction::URem: return bitc::BINOP_UREM;
709 case Instruction::FRem:
710 case Instruction::SRem: return bitc::BINOP_SREM;
711 case Instruction::Shl: return bitc::BINOP_SHL;
712 case Instruction::LShr: return bitc::BINOP_LSHR;
713 case Instruction::AShr: return bitc::BINOP_ASHR;
714 case Instruction::And: return bitc::BINOP_AND;
715 case Instruction::Or: return bitc::BINOP_OR;
716 case Instruction::Xor: return bitc::BINOP_XOR;
717 }
718}
719
720static unsigned getEncodedRMWOperation(const AtomicRMWInst &I) {
721 unsigned Encoding = 0;
722 switch (I.getOperation()) {
723 default: llvm_unreachable("Unknown RMW operation!");
725 Encoding = bitc::RMW_XCHG;
726 break;
728 Encoding = bitc::RMW_ADD;
729 break;
731 Encoding = bitc::RMW_SUB;
732 break;
734 Encoding = bitc::RMW_AND;
735 break;
737 Encoding = bitc::RMW_NAND;
738 break;
740 Encoding = bitc::RMW_OR;
741 break;
743 Encoding = bitc::RMW_XOR;
744 break;
746 Encoding = bitc::RMW_MAX;
747 break;
749 Encoding = bitc::RMW_MIN;
750 break;
752 Encoding = bitc::RMW_UMAX;
753 break;
755 Encoding = bitc::RMW_UMIN;
756 break;
758 Encoding = bitc::RMW_FADD;
759 break;
761 Encoding = bitc::RMW_FSUB;
762 break;
764 Encoding = bitc::RMW_FMAX;
765 break;
767 Encoding = bitc::RMW_FMIN;
768 break;
770 Encoding = bitc::RMW_FMAXIMUM;
771 break;
773 Encoding = bitc::RMW_FMINIMUM;
774 break;
776 Encoding = bitc::RMW_FMAXIMUMNUM;
777 break;
779 Encoding = bitc::RMW_FMINIMUMNUM;
780 break;
782 Encoding = bitc::RMW_UINC_WRAP;
783 break;
785 Encoding = bitc::RMW_UDEC_WRAP;
786 break;
788 Encoding = bitc::RMW_USUB_COND;
789 break;
791 Encoding = bitc::RMW_USUB_SAT;
792 break;
793 }
794
795 if (I.isElementwise())
796 Encoding |= bitc::RMW_ELEMENTWISE_FLAG;
797 return Encoding;
798}
799
812
813static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
814 StringRef Str, unsigned AbbrevToUse) {
816
817 // Code: [strchar x N]
818 for (char C : Str) {
819 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
820 AbbrevToUse = 0;
821 Vals.push_back(C);
822 }
823
824 // Emit the finished record.
825 Stream.EmitRecord(Code, Vals, AbbrevToUse);
826}
827
829 switch (Kind) {
830 case Attribute::Alignment:
832 case Attribute::AllocAlign:
834 case Attribute::AllocSize:
836 case Attribute::AlwaysInline:
838 case Attribute::Builtin:
840 case Attribute::ByVal:
842 case Attribute::Convergent:
844 case Attribute::InAlloca:
846 case Attribute::Cold:
848 case Attribute::DisableSanitizerInstrumentation:
850 case Attribute::FnRetThunkExtern:
852 case Attribute::Flatten:
854 case Attribute::Hot:
855 return bitc::ATTR_KIND_HOT;
856 case Attribute::ElementType:
858 case Attribute::HybridPatchable:
860 case Attribute::InlineHint:
862 case Attribute::InReg:
864 case Attribute::JumpTable:
866 case Attribute::MinSize:
868 case Attribute::AllocatedPointer:
870 case Attribute::AllocKind:
872 case Attribute::Memory:
874 case Attribute::NoFPClass:
876 case Attribute::Naked:
878 case Attribute::Nest:
880 case Attribute::NoAlias:
882 case Attribute::NoBuiltin:
884 case Attribute::NoCallback:
886 case Attribute::NoDivergenceSource:
888 case Attribute::NoDuplicate:
890 case Attribute::NoFree:
892 case Attribute::NoFreeObj:
894 case Attribute::NoImplicitFloat:
896 case Attribute::NoInline:
898 case Attribute::NoRecurse:
900 case Attribute::NoMerge:
902 case Attribute::NonLazyBind:
904 case Attribute::NonNull:
906 case Attribute::Dereferenceable:
908 case Attribute::DereferenceableOrNull:
910 case Attribute::NoRedZone:
912 case Attribute::NoReturn:
914 case Attribute::NoSync:
916 case Attribute::NoCfCheck:
918 case Attribute::NoProfile:
920 case Attribute::SkipProfile:
922 case Attribute::NoUnwind:
924 case Attribute::NoSanitizeBounds:
926 case Attribute::NoSanitizeCoverage:
928 case Attribute::NullPointerIsValid:
930 case Attribute::OptimizeForDebugging:
932 case Attribute::OptForFuzzing:
934 case Attribute::OptimizeForSize:
936 case Attribute::OptimizeNone:
938 case Attribute::ReadNone:
940 case Attribute::ReadOnly:
942 case Attribute::Returned:
944 case Attribute::ReturnsTwice:
946 case Attribute::SExt:
948 case Attribute::Speculatable:
950 case Attribute::StackAlignment:
952 case Attribute::StackProtect:
954 case Attribute::StackProtectReq:
956 case Attribute::StackProtectStrong:
958 case Attribute::SafeStack:
960 case Attribute::ShadowCallStack:
962 case Attribute::StrictFP:
964 case Attribute::StructRet:
966 case Attribute::SanitizeAddress:
968 case Attribute::SanitizeAllocToken:
970 case Attribute::SanitizeHWAddress:
972 case Attribute::SanitizeThread:
974 case Attribute::SanitizeConcurrency:
976 case Attribute::SanitizeType:
978 case Attribute::SanitizeMemory:
980 case Attribute::SanitizeNumericalStability:
982 case Attribute::SanitizeRealtime:
984 case Attribute::SanitizeRealtimeBlocking:
986 case Attribute::SpeculativeLoadHardening:
988 case Attribute::SwiftError:
990 case Attribute::SwiftSelf:
992 case Attribute::SwiftAsync:
994 case Attribute::UWTable:
996 case Attribute::VScaleRange:
998 case Attribute::WillReturn:
1000 case Attribute::WriteOnly:
1002 case Attribute::ZExt:
1003 return bitc::ATTR_KIND_Z_EXT;
1004 case Attribute::ImmArg:
1006 case Attribute::SanitizeMemTag:
1008 case Attribute::Preallocated:
1010 case Attribute::NoUndef:
1012 case Attribute::ByRef:
1013 return bitc::ATTR_KIND_BYREF;
1014 case Attribute::MustProgress:
1016 case Attribute::PresplitCoroutine:
1018 case Attribute::Writable:
1020 case Attribute::CoroDestroyOnlyWhenComplete:
1022 case Attribute::CoroElideSafe:
1024 case Attribute::DeadOnUnwind:
1026 case Attribute::Range:
1027 return bitc::ATTR_KIND_RANGE;
1028 case Attribute::Initializes:
1030 case Attribute::NoExt:
1032 case Attribute::Captures:
1034 case Attribute::DeadOnReturn:
1036 case Attribute::NoCreateUndefOrPoison:
1038 case Attribute::DenormalFPEnv:
1040 case Attribute::NoOutline:
1042 case Attribute::NoIPA:
1043 return bitc::ATTR_KIND_NOIPA;
1045 llvm_unreachable("Can not encode end-attribute kinds marker.");
1046 case Attribute::None:
1047 llvm_unreachable("Can not encode none-attribute.");
1050 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
1051 }
1052
1053 llvm_unreachable("Trying to encode unknown attribute");
1054}
1055
1057 if ((int64_t)V >= 0)
1058 Vals.push_back(V << 1);
1059 else
1060 Vals.push_back((-V << 1) | 1);
1061}
1062
1064 // We have an arbitrary precision integer value to write whose
1065 // bit width is > 64. However, in canonical unsigned integer
1066 // format it is likely that the high bits are going to be zero.
1067 // So, we only write the number of active words.
1068 unsigned NumWords = A.getActiveWords();
1069 const uint64_t *RawData = A.getRawData();
1070 for (unsigned i = 0; i < NumWords; i++)
1071 emitSignedInt64(Vals, RawData[i]);
1072}
1073
1075 const ConstantRange &CR, bool EmitBitWidth) {
1076 unsigned BitWidth = CR.getBitWidth();
1077 if (EmitBitWidth)
1078 Record.push_back(BitWidth);
1079 if (BitWidth > 64) {
1080 Record.push_back(CR.getLower().getActiveWords() |
1081 (uint64_t(CR.getUpper().getActiveWords()) << 32));
1084 } else {
1087 }
1088}
1089
1090void ModuleBitcodeWriter::writeAttributeGroupTable() {
1091 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1092 VE.getAttributeGroups();
1093 if (AttrGrps.empty()) return;
1094
1096
1097 SmallVector<uint64_t, 64> Record;
1098 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
1099 unsigned AttrListIndex = Pair.first;
1100 AttributeSet AS = Pair.second;
1101 Record.push_back(VE.getAttributeGroupID(Pair));
1102 Record.push_back(AttrListIndex);
1103
1104 for (Attribute Attr : AS) {
1105 if (Attr.isEnumAttribute()) {
1106 Record.push_back(0);
1107 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1108 } else if (Attr.isIntAttribute()) {
1109 Record.push_back(1);
1110 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1111 Record.push_back(getAttrKindEncoding(Kind));
1112 if (Kind == Attribute::Memory) {
1113 // Version field for upgrading old memory effects.
1114 const uint64_t Version = 2;
1115 Record.push_back((Version << 56) | Attr.getValueAsInt());
1116 } else {
1117 Record.push_back(Attr.getValueAsInt());
1118 }
1119 } else if (Attr.isStringAttribute()) {
1120 StringRef Kind = Attr.getKindAsString();
1121 StringRef Val = Attr.getValueAsString();
1122
1123 Record.push_back(Val.empty() ? 3 : 4);
1124 Record.append(Kind.begin(), Kind.end());
1125 Record.push_back(0);
1126 if (!Val.empty()) {
1127 Record.append(Val.begin(), Val.end());
1128 Record.push_back(0);
1129 }
1130 } else if (Attr.isTypeAttribute()) {
1131 Type *Ty = Attr.getValueAsType();
1132 Record.push_back(Ty ? 6 : 5);
1133 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1134 if (Ty)
1135 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
1136 } else if (Attr.isConstantRangeAttribute()) {
1137 Record.push_back(7);
1138 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1139 emitConstantRange(Record, Attr.getValueAsConstantRange(),
1140 /*EmitBitWidth=*/true);
1141 } else {
1142 assert(Attr.isConstantRangeListAttribute());
1143 Record.push_back(8);
1144 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1145 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
1146 Record.push_back(Val.size());
1147 Record.push_back(Val[0].getBitWidth());
1148 for (auto &CR : Val)
1149 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
1150 }
1151 }
1152
1154 Record.clear();
1155 }
1156
1157 Stream.ExitBlock();
1158}
1159
1160void ModuleBitcodeWriter::writeAttributeTable() {
1161 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
1162 if (Attrs.empty()) return;
1163
1165
1166 SmallVector<uint64_t, 64> Record;
1167 for (const AttributeList &AL : Attrs) {
1168 for (unsigned i : AL.indexes()) {
1169 AttributeSet AS = AL.getAttributes(i);
1170 if (AS.hasAttributes())
1171 Record.push_back(VE.getAttributeGroupID({i, AS}));
1172 }
1173
1174 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
1175 Record.clear();
1176 }
1177
1178 Stream.ExitBlock();
1179}
1180
1181/// WriteTypeTable - Write out the type table for a module.
1182void ModuleBitcodeWriter::writeTypeTable() {
1183 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1184
1185 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1186 SmallVector<uint64_t, 64> TypeVals;
1187
1189
1190 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1191 auto Abbv = std::make_shared<BitCodeAbbrev>();
1192 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
1193 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1194 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1195
1196 // Abbrev for TYPE_CODE_FUNCTION.
1197 Abbv = std::make_shared<BitCodeAbbrev>();
1198 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
1199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1202 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1203
1204 // Abbrev for TYPE_CODE_STRUCT_ANON.
1205 Abbv = std::make_shared<BitCodeAbbrev>();
1206 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
1207 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1210 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1211
1212 // Abbrev for TYPE_CODE_STRUCT_NAME.
1213 Abbv = std::make_shared<BitCodeAbbrev>();
1214 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
1215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1217 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1218
1219 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1220 Abbv = std::make_shared<BitCodeAbbrev>();
1221 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
1222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1225 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1226
1227 // Abbrev for TYPE_CODE_ARRAY.
1228 Abbv = std::make_shared<BitCodeAbbrev>();
1229 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
1230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1232 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1233
1234 // Emit an entry count so the reader can reserve space.
1235 TypeVals.push_back(TypeList.size());
1236 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1237 TypeVals.clear();
1238
1239 // Loop over all of the types, emitting each in turn.
1240 for (Type *T : TypeList) {
1241 int AbbrevToUse = 0;
1242 unsigned Code = 0;
1243
1244 switch (T->getTypeID()) {
1245 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
1246 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
1247 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;
1248 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
1249 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
1250 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
1251 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
1252 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
1253 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
1254 case Type::MetadataTyID:
1256 break;
1257 case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;
1258 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
1259 case Type::ByteTyID:
1260 // BYTE: [width]
1262 TypeVals.push_back(T->getByteBitWidth());
1263 break;
1264 case Type::IntegerTyID:
1265 // INTEGER: [width]
1268 break;
1269 case Type::PointerTyID: {
1271 unsigned AddressSpace = PTy->getAddressSpace();
1272 // OPAQUE_POINTER: [address space]
1274 TypeVals.push_back(AddressSpace);
1275 if (AddressSpace == 0)
1276 AbbrevToUse = OpaquePtrAbbrev;
1277 break;
1278 }
1279 case Type::FunctionTyID: {
1280 FunctionType *FT = cast<FunctionType>(T);
1281 // FUNCTION: [isvararg, retty, paramty x N]
1283 TypeVals.push_back(FT->isVarArg());
1284 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1285 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1286 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1287 AbbrevToUse = FunctionAbbrev;
1288 break;
1289 }
1290 case Type::StructTyID: {
1291 StructType *ST = cast<StructType>(T);
1292 // STRUCT: [ispacked, eltty x N]
1293 TypeVals.push_back(ST->isPacked());
1294 // Output all of the element types.
1295 for (Type *ET : ST->elements())
1296 TypeVals.push_back(VE.getTypeID(ET));
1297
1298 if (ST->isLiteral()) {
1300 AbbrevToUse = StructAnonAbbrev;
1301 } else {
1302 if (ST->isOpaque()) {
1304 } else {
1306 AbbrevToUse = StructNamedAbbrev;
1307 }
1308
1309 // Emit the name if it is present.
1310 if (!ST->getName().empty())
1312 StructNameAbbrev);
1313 }
1314 break;
1315 }
1316 case Type::ArrayTyID: {
1318 // ARRAY: [numelts, eltty]
1320 TypeVals.push_back(AT->getNumElements());
1321 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1322 AbbrevToUse = ArrayAbbrev;
1323 break;
1324 }
1325 case Type::FixedVectorTyID:
1326 case Type::ScalableVectorTyID: {
1328 // VECTOR [numelts, eltty] or
1329 // [numelts, eltty, scalable]
1331 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1332 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1334 TypeVals.push_back(true);
1335 break;
1336 }
1337 case Type::TargetExtTyID: {
1338 TargetExtType *TET = cast<TargetExtType>(T);
1341 StructNameAbbrev);
1342 TypeVals.push_back(TET->getNumTypeParameters());
1343 for (Type *InnerTy : TET->type_params())
1344 TypeVals.push_back(VE.getTypeID(InnerTy));
1345 llvm::append_range(TypeVals, TET->int_params());
1346 break;
1347 }
1348 case Type::TypedPointerTyID:
1349 llvm_unreachable("Typed pointers cannot be added to IR modules");
1350 }
1351
1352 // Emit the finished record.
1353 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1354 TypeVals.clear();
1355 }
1356
1357 Stream.ExitBlock();
1358}
1359
1361 switch (Linkage) {
1363 return 0;
1365 return 16;
1367 return 2;
1369 return 3;
1371 return 18;
1373 return 7;
1375 return 8;
1377 return 9;
1379 return 17;
1381 return 19;
1383 return 12;
1384 }
1385 llvm_unreachable("Invalid linkage");
1386}
1387
1388static unsigned getEncodedLinkage(const GlobalValue &GV) {
1389 return getEncodedLinkage(GV.getLinkage());
1390}
1391
1393 uint64_t RawFlags = 0;
1394 RawFlags |= Flags.ReadNone;
1395 RawFlags |= (Flags.ReadOnly << 1);
1396 RawFlags |= (Flags.NoRecurse << 2);
1397 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1398 RawFlags |= (Flags.NoInline << 4);
1399 RawFlags |= (Flags.AlwaysInline << 5);
1400 RawFlags |= (Flags.NoUnwind << 6);
1401 RawFlags |= (Flags.MayThrow << 7);
1402 RawFlags |= (Flags.HasUnknownCall << 8);
1403 RawFlags |= (Flags.MustBeUnreachable << 9);
1404 return RawFlags;
1405}
1406
1407// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1408// in BitcodeReader.cpp.
1410 bool ImportAsDecl = false) {
1411 uint64_t RawFlags = 0;
1412
1413 RawFlags |= Flags.NotEligibleToImport; // bool
1414 RawFlags |= (Flags.Live << 1);
1415 RawFlags |= (Flags.DSOLocal << 2);
1416 RawFlags |= (Flags.CanAutoHide << 3);
1417
1418 // Linkage don't need to be remapped at that time for the summary. Any future
1419 // change to the getEncodedLinkage() function will need to be taken into
1420 // account here as well.
1421 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1422
1423 RawFlags |= (Flags.Visibility << 8); // 2 bits
1424
1425 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1426 RawFlags |= (ImportType << 10); // 1 bit
1427
1428 RawFlags |= (Flags.NoRenameOnPromotion << 11); // 1 bit
1429
1430 return RawFlags;
1431}
1432
1434 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1435 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1436 return RawFlags;
1437}
1438
1440 uint64_t RawFlags = 0;
1441
1442 RawFlags |= CI.Hotness; // 3 bits
1443 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1444 RawFlags |= (CI.HasIndirectCall << 4); // 1 bit
1445
1446 return RawFlags;
1447}
1448
1449static unsigned getEncodedVisibility(const GlobalValue &GV) {
1450 switch (GV.getVisibility()) {
1451 case GlobalValue::DefaultVisibility: return 0;
1452 case GlobalValue::HiddenVisibility: return 1;
1453 case GlobalValue::ProtectedVisibility: return 2;
1454 }
1455 llvm_unreachable("Invalid visibility");
1456}
1457
1458static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1459 switch (GV.getDLLStorageClass()) {
1460 case GlobalValue::DefaultStorageClass: return 0;
1463 }
1464 llvm_unreachable("Invalid DLL storage class");
1465}
1466
1467static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1468 switch (GV.getThreadLocalMode()) {
1469 case GlobalVariable::NotThreadLocal: return 0;
1473 case GlobalVariable::LocalExecTLSModel: return 4;
1474 }
1475 llvm_unreachable("Invalid TLS model");
1476}
1477
1478static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1479 switch (C.getSelectionKind()) {
1480 case Comdat::Any:
1482 case Comdat::ExactMatch:
1484 case Comdat::Largest:
1488 case Comdat::SameSize:
1490 }
1491 llvm_unreachable("Invalid selection kind");
1492}
1493
1494static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1495 switch (GV.getUnnamedAddr()) {
1496 case GlobalValue::UnnamedAddr::None: return 0;
1497 case GlobalValue::UnnamedAddr::Local: return 2;
1498 case GlobalValue::UnnamedAddr::Global: return 1;
1499 }
1500 llvm_unreachable("Invalid unnamed_addr");
1501}
1502
1503size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1504 if (GenerateHash)
1505 Hasher.update(Str);
1506 return StrtabBuilder.add(Str);
1507}
1508
1509void ModuleBitcodeWriter::writeComdats() {
1511 for (const Comdat *C : VE.getComdats()) {
1512 // COMDAT: [strtab offset, strtab size, selection_kind]
1513 Vals.push_back(addToStrtab(C->getName()));
1514 Vals.push_back(C->getName().size());
1516 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1517 Vals.clear();
1518 }
1519}
1520
1521/// Write a record that will eventually hold the word offset of the
1522/// module-level VST. For now the offset is 0, which will be backpatched
1523/// after the real VST is written. Saves the bit offset to backpatch.
1524void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1525 // Write a placeholder value in for the offset of the real VST,
1526 // which is written after the function blocks so that it can include
1527 // the offset of each function. The placeholder offset will be
1528 // updated when the real VST is written.
1529 auto Abbv = std::make_shared<BitCodeAbbrev>();
1530 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1531 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1532 // hold the real VST offset. Must use fixed instead of VBR as we don't
1533 // know how many VBR chunks to reserve ahead of time.
1534 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1535 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1536
1537 // Emit the placeholder
1539 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1540
1541 // Compute and save the bit offset to the placeholder, which will be
1542 // patched when the real VST is written. We can simply subtract the 32-bit
1543 // fixed size from the current bit number to get the location to backpatch.
1544 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1545}
1546
1548
1549/// Determine the encoding to use for the given string name and length.
1551 bool isChar6 = true;
1552 for (char C : Str) {
1553 if (isChar6)
1554 isChar6 = BitCodeAbbrevOp::isChar6(C);
1555 if ((unsigned char)C & 128)
1556 // don't bother scanning the rest.
1557 return SE_Fixed8;
1558 }
1559 if (isChar6)
1560 return SE_Char6;
1561 return SE_Fixed7;
1562}
1563
1564static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1565 "Sanitizer Metadata is too large for naive serialization.");
1566static unsigned
1568 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1569 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1570}
1571
1572/// Emit top-level description of module, including target triple, inline asm,
1573/// descriptors for global variables, and function prototype info.
1574/// Returns the bit offset to backpatch with the location of the real VST.
1575void ModuleBitcodeWriter::writeModuleInfo() {
1576 // Emit various pieces of data attached to a module.
1577 if (!M.getTargetTriple().empty())
1579 M.getTargetTriple().str(), 0 /*TODO*/);
1580 const std::string &DL = M.getDataLayoutStr();
1581 if (!DL.empty())
1583
1584 for (const Module::GlobalAsmFragment &Frag : M.getModuleInlineAsm()) {
1586 Frag.Props.getAsStrings();
1587 for (auto [Key, Value] : Props) {
1589 Record.append(Key.begin(), Key.end());
1590 Record.push_back(0);
1591 Record.append(Value.begin(), Value.end());
1593 }
1594 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, Frag.Asm, 0 /*TODO*/);
1595 }
1596
1597 // Emit information about sections and GC, computing how many there are. Also
1598 // compute the maximum alignment value.
1599 std::map<std::string, unsigned> SectionMap;
1600 std::map<std::string, unsigned> GCMap;
1601 MaybeAlign MaxGVarAlignment;
1602 unsigned MaxGlobalType = 0;
1603 for (const GlobalVariable &GV : M.globals()) {
1604 if (MaybeAlign A = GV.getAlign())
1605 MaxGVarAlignment = !MaxGVarAlignment ? *A : std::max(*MaxGVarAlignment, *A);
1606 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1607 if (GV.hasSection()) {
1608 // Give section names unique ID's.
1609 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1610 if (!Entry) {
1611 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1612 0 /*TODO*/);
1613 Entry = SectionMap.size();
1614 }
1615 }
1616 }
1617 for (const Function &F : M) {
1618 if (F.hasSection()) {
1619 // Give section names unique ID's.
1620 unsigned &Entry = SectionMap[std::string(F.getSection())];
1621 if (!Entry) {
1623 0 /*TODO*/);
1624 Entry = SectionMap.size();
1625 }
1626 }
1627 if (F.hasGC()) {
1628 // Same for GC names.
1629 unsigned &Entry = GCMap[F.getGC()];
1630 if (!Entry) {
1632 0 /*TODO*/);
1633 Entry = GCMap.size();
1634 }
1635 }
1636 }
1637
1638 // Emit abbrev for globals, now that we know # sections and max alignment.
1639 unsigned SimpleGVarAbbrev = 0;
1640 if (!M.global_empty()) {
1641 // Add an abbrev for common globals with no visibility or thread localness.
1642 auto Abbv = std::make_shared<BitCodeAbbrev>();
1643 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1647 Log2_32_Ceil(MaxGlobalType+1)));
1648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1649 //| explicitType << 1
1650 //| constant
1651 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1652 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1653 if (!MaxGVarAlignment) // Alignment.
1654 Abbv->Add(BitCodeAbbrevOp(0));
1655 else {
1656 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1658 Log2_32_Ceil(MaxEncAlignment+1)));
1659 }
1660 if (SectionMap.empty()) // Section.
1661 Abbv->Add(BitCodeAbbrevOp(0));
1662 else
1663 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1664 Log2_32_Ceil(SectionMap.size()+1)));
1665 // Don't bother emitting vis + thread local.
1666 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1667 }
1668
1670 // Emit the module's source file name.
1671 {
1672 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1673 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1674 if (Bits == SE_Char6)
1675 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1676 else if (Bits == SE_Fixed7)
1677 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1678
1679 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1680 auto Abbv = std::make_shared<BitCodeAbbrev>();
1681 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1682 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1683 Abbv->Add(AbbrevOpToUse);
1684 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1685
1686 for (const auto P : M.getSourceFileName())
1687 Vals.push_back((unsigned char)P);
1688
1689 // Emit the finished record.
1690 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1691 Vals.clear();
1692 }
1693
1694 writeGUIDList();
1695
1696 // Emit the global variable information.
1697 for (const GlobalVariable &GV : M.globals()) {
1698 unsigned AbbrevToUse = 0;
1699
1700 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1701 // linkage, alignment, section, visibility, threadlocal,
1702 // unnamed_addr, externally_initialized, dllstorageclass,
1703 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1704 Vals.push_back(addToStrtab(GV.getName()));
1705 Vals.push_back(GV.getName().size());
1706 Vals.push_back(VE.getTypeID(GV.getValueType()));
1707 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1708 Vals.push_back(GV.isDeclaration() ? 0 :
1709 (VE.getValueID(GV.getInitializer()) + 1));
1710 Vals.push_back(getEncodedLinkage(GV));
1711 Vals.push_back(getEncodedAlign(GV.getAlign()));
1712 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1713 : 0);
1714 if (GV.isThreadLocal() ||
1715 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1716 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1717 GV.isExternallyInitialized() ||
1718 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1719 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1720 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1724 Vals.push_back(GV.isExternallyInitialized());
1726 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1727
1728 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1729 Vals.push_back(VE.getAttributeListID(AL));
1730
1731 Vals.push_back(GV.isDSOLocal());
1732 Vals.push_back(addToStrtab(GV.getPartition()));
1733 Vals.push_back(GV.getPartition().size());
1734
1735 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1736 GV.getSanitizerMetadata())
1737 : 0));
1738 Vals.push_back(GV.getCodeModelRaw());
1739 } else {
1740 AbbrevToUse = SimpleGVarAbbrev;
1741 }
1742
1743 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1744 Vals.clear();
1745 }
1746
1747 // Emit the function proto information.
1748 for (const Function &F : M) {
1749 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1750 // linkage, paramattrs, alignment, section, visibility, gc,
1751 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1752 // prefixdata, personalityfn, DSO_Local, addrspace,
1753 // partition_strtab, partition_size, prefalign]
1754 Vals.push_back(addToStrtab(F.getName()));
1755 Vals.push_back(F.getName().size());
1756 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1757 Vals.push_back(F.getCallingConv());
1758 Vals.push_back(F.isDeclaration());
1760 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1761 Vals.push_back(getEncodedAlign(F.getAlign()));
1762 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1763 : 0);
1765 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1767 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1768 : 0);
1770 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1771 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1772 : 0);
1773 Vals.push_back(
1774 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1775
1776 Vals.push_back(F.isDSOLocal());
1777 Vals.push_back(F.getAddressSpace());
1778 Vals.push_back(addToStrtab(F.getPartition()));
1779 Vals.push_back(F.getPartition().size());
1780 Vals.push_back(getEncodedAlign(F.getPreferredAlignment()));
1781
1782 unsigned AbbrevToUse = 0;
1783 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1784 Vals.clear();
1785 }
1786
1787 // Emit the alias information.
1788 for (const GlobalAlias &A : M.aliases()) {
1789 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1790 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1791 // DSO_Local]
1792 Vals.push_back(addToStrtab(A.getName()));
1793 Vals.push_back(A.getName().size());
1794 Vals.push_back(VE.getTypeID(A.getValueType()));
1795 Vals.push_back(A.getType()->getAddressSpace());
1796 Vals.push_back(VE.getValueID(A.getAliasee()));
1802 Vals.push_back(A.isDSOLocal());
1803 Vals.push_back(addToStrtab(A.getPartition()));
1804 Vals.push_back(A.getPartition().size());
1805
1806 unsigned AbbrevToUse = 0;
1807 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1808 Vals.clear();
1809 }
1810
1811 // Emit the ifunc information.
1812 for (const GlobalIFunc &I : M.ifuncs()) {
1813 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1814 // val#, linkage, visibility, DSO_Local]
1815 Vals.push_back(addToStrtab(I.getName()));
1816 Vals.push_back(I.getName().size());
1817 Vals.push_back(VE.getTypeID(I.getValueType()));
1818 Vals.push_back(I.getType()->getAddressSpace());
1819 Vals.push_back(VE.getValueID(I.getResolver()));
1822 Vals.push_back(I.isDSOLocal());
1823 Vals.push_back(addToStrtab(I.getPartition()));
1824 Vals.push_back(I.getPartition().size());
1825 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1826 Vals.clear();
1827 }
1828
1829 writeValueSymbolTableForwardDecl();
1830}
1831
1833 uint64_t Flags = 0;
1834
1835 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1836 if (OBO->hasNoSignedWrap())
1837 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1838 if (OBO->hasNoUnsignedWrap())
1839 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1840 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1841 if (PEO->isExact())
1842 Flags |= 1 << bitc::PEO_EXACT;
1843 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1844 if (PDI->isDisjoint())
1845 Flags |= 1 << bitc::PDI_DISJOINT;
1846 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1847 if (FPMO->hasAllowReassoc())
1848 Flags |= bitc::AllowReassoc;
1849 if (FPMO->hasNoNaNs())
1850 Flags |= bitc::NoNaNs;
1851 if (FPMO->hasNoInfs())
1852 Flags |= bitc::NoInfs;
1853 if (FPMO->hasNoSignedZeros())
1854 Flags |= bitc::NoSignedZeros;
1855 if (FPMO->hasAllowReciprocal())
1856 Flags |= bitc::AllowReciprocal;
1857 if (FPMO->hasAllowContract())
1858 Flags |= bitc::AllowContract;
1859 if (FPMO->hasApproxFunc())
1860 Flags |= bitc::ApproxFunc;
1861
1862 // Handle uitofp.
1863 if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1864 Flags <<= 1;
1865 if (NNI->hasNonNeg())
1866 Flags |= 1 << bitc::PNNI_NON_NEG;
1867 }
1868 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1869 if (NNI->hasNonNeg())
1870 Flags |= 1 << bitc::PNNI_NON_NEG;
1871 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1872 if (TI->hasNoSignedWrap())
1873 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1874 if (TI->hasNoUnsignedWrap())
1875 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1876 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1877 if (GEP->isInBounds())
1878 Flags |= 1 << bitc::GEP_INBOUNDS;
1879 if (GEP->hasNoUnsignedSignedWrap())
1880 Flags |= 1 << bitc::GEP_NUSW;
1881 if (GEP->hasNoUnsignedWrap())
1882 Flags |= 1 << bitc::GEP_NUW;
1883 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1884 if (ICmp->hasSameSign())
1885 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1886 } else if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(V)) {
1887 if (ASC->hasNonNull())
1888 Flags |= 1 << bitc::ASCI_NON_NULL;
1889 }
1890
1891 return Flags;
1892}
1893
1894void ModuleBitcodeWriter::writeValueAsMetadata(
1895 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1896 // Mimic an MDNode with a value as one operand.
1897 Value *V = MD->getValue();
1898 Record.push_back(VE.getTypeID(V->getType()));
1899 Record.push_back(VE.getValueID(V));
1900 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1901 Record.clear();
1902}
1903
1904void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1905 SmallVectorImpl<uint64_t> &Record,
1906 unsigned Abbrev) {
1907 for (const MDOperand &MDO : N->operands()) {
1908 Metadata *MD = MDO;
1909 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1910 "Unexpected function-local metadata");
1911 Record.push_back(VE.getMetadataOrNullID(MD));
1912 }
1913 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1915 Record, Abbrev);
1916 Record.clear();
1917}
1918
1919unsigned ModuleBitcodeWriter::createDILocationAbbrev(bool WithIRLayers) {
1920 // Assume the column is usually under 128, and always output the inlined-at
1921 // location (it's never more expensive than building an array size 1).
1922 //
1923 // Separate abbrev so a location without layers does not spend a VBR chunk
1924 // encoding a zero; writeDILocation picks between the two per record.
1925 auto Abbv = std::make_shared<BitCodeAbbrev>();
1926 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1927 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isDistinct
1928 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // line
1929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // column
1930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // scope
1931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // inlinedAt
1932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImplicitCode
1933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // atomGroup
1934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // atomRank
1935 if (WithIRLayers)
1936 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // irlayers
1937 return Stream.EmitAbbrev(std::move(Abbv));
1938}
1939
1940void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1941 SmallVectorImpl<uint64_t> &Record,
1942 unsigned &Abbrev) {
1943 if (!Abbrev)
1944 Abbrev = createDILocationAbbrev(/*WithIRLayers=*/false);
1945
1946 Record.push_back(N->isDistinct());
1947 Record.push_back(N->getLine());
1948 Record.push_back(N->getColumn());
1949 Record.push_back(VE.getMetadataID(N->getScope()));
1950 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1951 Record.push_back(N->isImplicitCode());
1952 Record.push_back(N->getAtomGroup());
1953 Record.push_back(N->getAtomRank());
1954
1955 unsigned AbbrevToUse = Abbrev;
1956 if (DILayerLocList *IRLayers = N->getIRLayers()) {
1957 if (!DILocationLayersAbbrev)
1958 DILocationLayersAbbrev = createDILocationAbbrev(/*WithIRLayers=*/true);
1959 AbbrevToUse = DILocationLayersAbbrev;
1960 Record.push_back(VE.getMetadataOrNullID(IRLayers));
1961 }
1962
1963 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, AbbrevToUse);
1964 Record.clear();
1965}
1966
1967void ModuleBitcodeWriter::writeDILayerLoc(const DILayerLoc *N,
1968 SmallVectorImpl<uint64_t> &Record,
1969 unsigned Abbrev) {
1970 Record.push_back(N->isDistinct());
1971 Record.push_back(N->getLine());
1972 Record.push_back(N->getColumn());
1973 Record.push_back(VE.getMetadataID(N->getRawFile()));
1974 Record.push_back(VE.getMetadataID(N->getRawKind()));
1975 Stream.EmitRecord(bitc::METADATA_LAYERLOC, Record, Abbrev);
1976 Record.clear();
1977}
1978
1979void ModuleBitcodeWriter::writeDILayerLocList(const DILayerLocList *N,
1980 SmallVectorImpl<uint64_t> &Record,
1981 unsigned Abbrev) {
1982 Record.push_back(N->isDistinct());
1983 for (const MDOperand &Op : N->layers())
1984 Record.push_back(VE.getMetadataID(Op.get()));
1985 Stream.EmitRecord(bitc::METADATA_LAYERLOCLIST, Record, Abbrev);
1986 Record.clear();
1987}
1988
1989unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1990 // Assume the column is usually under 128, and always output the inlined-at
1991 // location (it's never more expensive than building an array size 1).
1992 auto Abbv = std::make_shared<BitCodeAbbrev>();
1993 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1997 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2000 return Stream.EmitAbbrev(std::move(Abbv));
2001}
2002
2003void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
2004 SmallVectorImpl<uint64_t> &Record,
2005 unsigned &Abbrev) {
2006 if (!Abbrev)
2007 Abbrev = createGenericDINodeAbbrev();
2008
2009 Record.push_back(N->isDistinct());
2010 Record.push_back(N->getTag());
2011 Record.push_back(0); // Per-tag version field; unused for now.
2012
2013 for (auto &I : N->operands())
2014 Record.push_back(VE.getMetadataOrNullID(I));
2015
2016 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
2017 Record.clear();
2018}
2019
2020void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
2021 SmallVectorImpl<uint64_t> &Record,
2022 unsigned Abbrev) {
2023 const uint64_t Version = 2 << 1;
2024 Record.push_back((uint64_t)N->isDistinct() | Version);
2025 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
2026 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2027 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2028 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2029
2030 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
2031 Record.clear();
2032}
2033
2034void ModuleBitcodeWriter::writeDIGenericSubrange(
2035 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
2036 unsigned Abbrev) {
2037 Record.push_back((uint64_t)N->isDistinct());
2038 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
2039 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2040 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2041 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2042
2043 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
2044 Record.clear();
2045}
2046
2047void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
2048 SmallVectorImpl<uint64_t> &Record,
2049 unsigned Abbrev) {
2050 const uint64_t IsBigInt = 1 << 2;
2051 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
2052 Record.push_back(N->getValue().getBitWidth());
2053 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2054 emitWideAPInt(Record, N->getValue());
2055
2056 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
2057 Record.clear();
2058}
2059
2060void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
2061 SmallVectorImpl<uint64_t> &Record,
2062 unsigned Abbrev) {
2063 const unsigned SizeIsMetadata = 0x2;
2064 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2065 Record.push_back(N->getTag());
2066 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2067 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2068 Record.push_back(N->getAlignInBits());
2069 Record.push_back(N->getEncoding());
2070 Record.push_back(N->getFlags());
2071 Record.push_back(N->getNumExtraInhabitants());
2072 Record.push_back(N->getDataSizeInBits());
2073 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2074 Record.push_back(N->getLine());
2075 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2076
2077 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
2078 Record.clear();
2079}
2080
2081void ModuleBitcodeWriter::writeDIFixedPointType(
2082 const DIFixedPointType *N, SmallVectorImpl<uint64_t> &Record,
2083 unsigned Abbrev) {
2084 const unsigned SizeIsMetadata = 0x2;
2085 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2086 Record.push_back(N->getTag());
2087 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2088 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2089 Record.push_back(N->getAlignInBits());
2090 Record.push_back(N->getEncoding());
2091 Record.push_back(N->getFlags());
2092 Record.push_back(N->getKind());
2093 Record.push_back(N->getFactorRaw());
2094
2095 auto WriteWideInt = [&](const APInt &Value) {
2096 // Write an encoded word that holds the number of active words and
2097 // the number of bits.
2098 uint64_t NumWords = Value.getActiveWords();
2099 uint64_t Encoded = (NumWords << 32) | Value.getBitWidth();
2100 Record.push_back(Encoded);
2101 emitWideAPInt(Record, Value);
2102 };
2103
2104 WriteWideInt(N->getNumeratorRaw());
2105 WriteWideInt(N->getDenominatorRaw());
2106
2107 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2108 Record.push_back(N->getLine());
2109 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2110
2111 Stream.EmitRecord(bitc::METADATA_FIXED_POINT_TYPE, Record, Abbrev);
2112 Record.clear();
2113}
2114
2115void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
2116 SmallVectorImpl<uint64_t> &Record,
2117 unsigned Abbrev) {
2118 const unsigned SizeIsMetadata = 0x2;
2119 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2120 Record.push_back(N->getTag());
2121 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2122 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
2123 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
2124 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
2125 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2126 Record.push_back(N->getAlignInBits());
2127 Record.push_back(N->getEncoding());
2128 Record.push_back(VE.getMetadataOrNullID(N->getRawCharType()));
2129
2130 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
2131 Record.clear();
2132}
2133
2134void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
2135 SmallVectorImpl<uint64_t> &Record,
2136 unsigned Abbrev) {
2137 const unsigned SizeIsMetadata = 0x2;
2138 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2139 Record.push_back(N->getTag());
2140 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2141 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2142 Record.push_back(N->getLine());
2143 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2144 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2145 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2146 Record.push_back(N->getAlignInBits());
2147 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2148 Record.push_back(N->getFlags());
2149 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
2150
2151 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
2152 // that there is no DWARF address space associated with DIDerivedType.
2153 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2154 Record.push_back(*DWARFAddressSpace + 1);
2155 else
2156 Record.push_back(0);
2157
2158 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2159
2160 if (auto PtrAuthData = N->getPtrAuthData())
2161 Record.push_back(PtrAuthData->RawData);
2162 else
2163 Record.push_back(0);
2164
2165 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
2166 Record.clear();
2167}
2168
2169void ModuleBitcodeWriter::writeDISubrangeType(const DISubrangeType *N,
2170 SmallVectorImpl<uint64_t> &Record,
2171 unsigned Abbrev) {
2172 const unsigned SizeIsMetadata = 0x2;
2173 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2174 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2175 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2176 Record.push_back(N->getLine());
2177 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2178 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2179 Record.push_back(N->getAlignInBits());
2180 Record.push_back(N->getFlags());
2181 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2182 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2183 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2184 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2185 Record.push_back(VE.getMetadataOrNullID(N->getRawBias()));
2186
2187 Stream.EmitRecord(bitc::METADATA_SUBRANGE_TYPE, Record, Abbrev);
2188 Record.clear();
2189}
2190
2191void ModuleBitcodeWriter::writeDICompositeType(
2192 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
2193 unsigned Abbrev) {
2194 const unsigned IsNotUsedInOldTypeRef = 0x2;
2195 const unsigned SizeIsMetadata = 0x4;
2196 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2197 (unsigned)N->isDistinct());
2198 Record.push_back(N->getTag());
2199 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2200 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2201 Record.push_back(N->getLine());
2202 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2203 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2204 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2205 Record.push_back(N->getAlignInBits());
2206 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2207 Record.push_back(N->getFlags());
2208 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2209 Record.push_back(N->getRuntimeLang());
2210 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
2211 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2212 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
2213 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
2214 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
2215 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
2216 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
2217 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
2218 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2219 Record.push_back(N->getNumExtraInhabitants());
2220 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
2221 Record.push_back(
2222 N->getEnumKind().value_or(dwarf::DW_APPLE_ENUM_KIND_invalid));
2223 Record.push_back(VE.getMetadataOrNullID(N->getRawBitStride()));
2224
2225 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
2226 Record.clear();
2227}
2228
2229void ModuleBitcodeWriter::writeDISubroutineType(
2230 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
2231 unsigned Abbrev) {
2232 const unsigned HasNoOldTypeRefs = 0x2;
2233 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
2234 Record.push_back(N->getFlags());
2235 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
2236 Record.push_back(N->getCC());
2237
2238 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
2239 Record.clear();
2240}
2241
2242void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
2243 SmallVectorImpl<uint64_t> &Record,
2244 unsigned Abbrev) {
2245 Record.push_back(N->isDistinct());
2246 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
2247 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
2248 if (N->getRawChecksum()) {
2249 Record.push_back(N->getRawChecksum()->Kind);
2250 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
2251 } else {
2252 // Maintain backwards compatibility with the old internal representation of
2253 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
2254 Record.push_back(0);
2255 Record.push_back(VE.getMetadataOrNullID(nullptr));
2256 }
2257 auto Source = N->getRawSource();
2258 if (Source)
2259 Record.push_back(VE.getMetadataOrNullID(Source));
2260
2261 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
2262 Record.clear();
2263}
2264
2265void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2266 SmallVectorImpl<uint64_t> &Record,
2267 unsigned Abbrev) {
2268 assert(N->isDistinct() && "Expected distinct compile units");
2269 Record.push_back(/* IsDistinct */ true);
2270
2271 auto Lang = N->getSourceLanguage();
2272 Record.push_back(Lang.getName());
2273 // Set bit so the MetadataLoader can distniguish between versioned and
2274 // unversioned names.
2275 if (Lang.hasVersionedName())
2276 Record.back() ^= (uint64_t(1) << 63);
2277
2278 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2279 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2280 Record.push_back(N->isOptimized());
2281 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2282 Record.push_back(N->getRuntimeVersion());
2283 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2284 Record.push_back(N->getEmissionKind());
2285 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2286 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2287 Record.push_back(/* subprograms */ 0);
2288 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2289 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2290 Record.push_back(N->getDWOId());
2291 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2292 Record.push_back(N->getSplitDebugInlining());
2293 Record.push_back(N->getDebugInfoForProfiling());
2294 Record.push_back((unsigned)N->getNameTableKind());
2295 Record.push_back(N->getRangesBaseAddress());
2296 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2297 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2298 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2299 Record.push_back(Lang.getDialect());
2300
2301 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
2302 Record.clear();
2303}
2304
2305void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2306 SmallVectorImpl<uint64_t> &Record,
2307 unsigned Abbrev) {
2308 const uint64_t HasUnitFlag = 1 << 1;
2309 const uint64_t HasSPFlagsFlag = 1 << 2;
2310 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2311 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2312 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2313 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2314 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2315 Record.push_back(N->getLine());
2316 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2317 Record.push_back(N->getScopeLine());
2318 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2319 Record.push_back(N->getSPFlags());
2320 Record.push_back(N->getVirtualIndex());
2321 Record.push_back(N->getFlags());
2322 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2323 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2324 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2325 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2326 Record.push_back(N->getThisAdjustment());
2327 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2328 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2329 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2330 Record.push_back(N->getKeyInstructionsEnabled());
2331
2332 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
2333 Record.clear();
2334}
2335
2336void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2337 SmallVectorImpl<uint64_t> &Record,
2338 unsigned Abbrev) {
2339 Record.push_back(N->isDistinct());
2340 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2341 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2342 Record.push_back(N->getLine());
2343 Record.push_back(N->getColumn());
2344
2345 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
2346 Record.clear();
2347}
2348
2349void ModuleBitcodeWriter::writeDILexicalBlockFile(
2350 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
2351 unsigned Abbrev) {
2352 Record.push_back(N->isDistinct());
2353 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2354 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2355 Record.push_back(N->getDiscriminator());
2356
2357 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
2358 Record.clear();
2359}
2360
2361void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2362 SmallVectorImpl<uint64_t> &Record,
2363 unsigned Abbrev) {
2364 Record.push_back(N->isDistinct());
2365 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2366 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2367 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2368 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2369 Record.push_back(N->getLineNo());
2370
2371 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2372 Record.clear();
2373}
2374
2375void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2376 SmallVectorImpl<uint64_t> &Record,
2377 unsigned Abbrev) {
2378 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2379 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2380 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2381
2382 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
2383 Record.clear();
2384}
2385
2386void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2387 SmallVectorImpl<uint64_t> &Record,
2388 unsigned Abbrev) {
2389 Record.push_back(N->isDistinct());
2390 Record.push_back(N->getMacinfoType());
2391 Record.push_back(N->getLine());
2392 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2393 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2394
2395 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2396 Record.clear();
2397}
2398
2399void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2400 SmallVectorImpl<uint64_t> &Record,
2401 unsigned Abbrev) {
2402 Record.push_back(N->isDistinct());
2403 Record.push_back(N->getMacinfoType());
2404 Record.push_back(N->getLine());
2405 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2406 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2407
2408 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2409 Record.clear();
2410}
2411
2412void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2413 SmallVectorImpl<uint64_t> &Record) {
2414 Record.reserve(N->getArgs().size());
2415 for (ValueAsMetadata *MD : N->getArgs())
2416 Record.push_back(VE.getMetadataID(MD));
2417
2418 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2419 Record.clear();
2420}
2421
2422void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2423 SmallVectorImpl<uint64_t> &Record,
2424 unsigned Abbrev) {
2425 Record.push_back(N->isDistinct());
2426 for (auto &I : N->operands())
2427 Record.push_back(VE.getMetadataOrNullID(I));
2428 Record.push_back(N->getLineNo());
2429 Record.push_back(N->getIsDecl());
2430
2431 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2432 Record.clear();
2433}
2434
2435void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2436 SmallVectorImpl<uint64_t> &Record,
2437 unsigned Abbrev) {
2438 // There are no arguments for this metadata type.
2439 Record.push_back(N->isDistinct());
2440 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2441 Record.clear();
2442}
2443
2444void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2445 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
2446 unsigned Abbrev) {
2447 Record.push_back(N->isDistinct());
2448 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2449 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2450 Record.push_back(N->isDefault());
2451
2452 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
2453 Record.clear();
2454}
2455
2456void ModuleBitcodeWriter::writeDITemplateValueParameter(
2457 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
2458 unsigned Abbrev) {
2459 Record.push_back(N->isDistinct());
2460 Record.push_back(N->getTag());
2461 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2462 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2463 Record.push_back(N->isDefault());
2464 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2465
2466 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
2467 Record.clear();
2468}
2469
2470void ModuleBitcodeWriter::writeDIGlobalVariable(
2471 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
2472 unsigned Abbrev) {
2473 const uint64_t Version = 2 << 1;
2474 Record.push_back((uint64_t)N->isDistinct() | Version);
2475 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2476 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2477 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2478 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2479 Record.push_back(N->getLine());
2480 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2481 Record.push_back(N->isLocalToUnit());
2482 Record.push_back(N->isDefinition());
2483 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2484 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2485 Record.push_back(N->getAlignInBits());
2486 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2487
2488 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2489 Record.clear();
2490}
2491
2492void ModuleBitcodeWriter::writeDILocalVariable(
2493 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
2494 unsigned Abbrev) {
2495 // In order to support all possible bitcode formats in BitcodeReader we need
2496 // to distinguish the following cases:
2497 // 1) Record has no artificial tag (Record[1]),
2498 // has no obsolete inlinedAt field (Record[9]).
2499 // In this case Record size will be 8, HasAlignment flag is false.
2500 // 2) Record has artificial tag (Record[1]),
2501 // has no obsolete inlignedAt field (Record[9]).
2502 // In this case Record size will be 9, HasAlignment flag is false.
2503 // 3) Record has both artificial tag (Record[1]) and
2504 // obsolete inlignedAt field (Record[9]).
2505 // In this case Record size will be 10, HasAlignment flag is false.
2506 // 4) Record has neither artificial tag, nor inlignedAt field, but
2507 // HasAlignment flag is true and Record[8] contains alignment value.
2508 const uint64_t HasAlignmentFlag = 1 << 1;
2509 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2510 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2511 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2512 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2513 Record.push_back(N->getLine());
2514 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2515 Record.push_back(N->getArg());
2516 Record.push_back(N->getFlags());
2517 Record.push_back(N->getAlignInBits());
2518 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2519
2520 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2521 Record.clear();
2522}
2523
2524void ModuleBitcodeWriter::writeDILabel(
2525 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2526 unsigned Abbrev) {
2527 uint64_t IsArtificialFlag = uint64_t(N->isArtificial()) << 1;
2528 Record.push_back((uint64_t)N->isDistinct() | IsArtificialFlag);
2529 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2530 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2531 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2532 Record.push_back(N->getLine());
2533 Record.push_back(N->getColumn());
2534 Record.push_back(N->getCoroSuspendIdx().has_value()
2535 ? (uint64_t)N->getCoroSuspendIdx().value()
2536 : std::numeric_limits<uint64_t>::max());
2537
2538 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2539 Record.clear();
2540}
2541
2542void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2543 SmallVectorImpl<uint64_t> &Record,
2544 unsigned Abbrev) {
2545 Record.reserve(N->getElements().size() + 1);
2546 const uint64_t Version = 3 << 1;
2547 Record.push_back((uint64_t)N->isDistinct() | Version);
2548 Record.append(N->elements_begin(), N->elements_end());
2549
2550 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2551 Record.clear();
2552}
2553
2554void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2555 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2556 unsigned Abbrev) {
2557 Record.push_back(N->isDistinct());
2558 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2559 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2560
2561 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2562 Record.clear();
2563}
2564
2565void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2566 SmallVectorImpl<uint64_t> &Record,
2567 unsigned Abbrev) {
2568 Record.push_back(N->isDistinct());
2569 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2570 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2571 Record.push_back(N->getLine());
2572 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2573 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2574 Record.push_back(N->getAttributes());
2575 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2576
2577 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2578 Record.clear();
2579}
2580
2581void ModuleBitcodeWriter::writeDIProperty(const DIProperty *N,
2582 SmallVectorImpl<uint64_t> &Record,
2583 unsigned Abbrev) {
2584 Record.push_back(N->isDistinct());
2585 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2586 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2587 Record.push_back(N->getLine());
2588 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2589 Record.push_back(VE.getMetadataOrNullID(N->getBackingStorage()));
2590
2591 Stream.EmitRecord(bitc::METADATA_PROPERTY, Record, Abbrev);
2592 Record.clear();
2593}
2594
2595void ModuleBitcodeWriter::writeDIImportedEntity(
2596 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2597 unsigned Abbrev) {
2598 Record.push_back(N->isDistinct());
2599 Record.push_back(N->getTag());
2600 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2601 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2602 Record.push_back(N->getLine());
2603 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2604 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2605 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2606
2607 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2608 Record.clear();
2609}
2610
2611unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2612 auto Abbv = std::make_shared<BitCodeAbbrev>();
2613 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2614 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2616 return Stream.EmitAbbrev(std::move(Abbv));
2617}
2618
2619void ModuleBitcodeWriter::writeNamedMetadata(
2620 SmallVectorImpl<uint64_t> &Record) {
2621 if (M.named_metadata_empty())
2622 return;
2623
2624 unsigned Abbrev = createNamedMetadataAbbrev();
2625 for (const NamedMDNode &NMD : M.named_metadata()) {
2626 // Write name.
2627 StringRef Str = NMD.getName();
2628 Record.append(Str.bytes_begin(), Str.bytes_end());
2629 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2630 Record.clear();
2631
2632 // Write named metadata operands.
2633 for (const MDNode *N : NMD.operands())
2634 Record.push_back(VE.getMetadataID(N));
2635 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2636 Record.clear();
2637 }
2638}
2639
2640unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2641 auto Abbv = std::make_shared<BitCodeAbbrev>();
2642 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2643 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2646 return Stream.EmitAbbrev(std::move(Abbv));
2647}
2648
2649/// Write out a record for MDString.
2650///
2651/// All the metadata strings in a metadata block are emitted in a single
2652/// record. The sizes and strings themselves are shoved into a blob.
2653void ModuleBitcodeWriter::writeMetadataStrings(
2654 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2655 if (Strings.empty())
2656 return;
2657
2658 // Start the record with the number of strings.
2659 Record.push_back(bitc::METADATA_STRINGS);
2660 Record.push_back(Strings.size());
2661
2662 // Emit the sizes of the strings in the blob.
2663 SmallString<256> Blob;
2664 {
2665 BitstreamWriter W(Blob);
2666 for (const Metadata *MD : Strings)
2667 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2668 W.FlushToWord();
2669 }
2670
2671 // Add the offset to the strings to the record.
2672 Record.push_back(Blob.size());
2673
2674 // Add the strings to the blob.
2675 for (const Metadata *MD : Strings)
2676 Blob.append(cast<MDString>(MD)->getString());
2677
2678 // Emit the final record.
2679 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2680 Record.clear();
2681}
2682
2683// Generates an enum to use as an index in the Abbrev array of Metadata record.
2684enum MetadataAbbrev : unsigned {
2685#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2686#include "llvm/IR/Metadata.def"
2688};
2689
2690void ModuleBitcodeWriter::writeMetadataRecords(
2691 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2692 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2693 if (MDs.empty())
2694 return;
2695
2696 // Initialize MDNode abbreviations.
2697#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2698#include "llvm/IR/Metadata.def"
2699
2700 for (const Metadata *MD : MDs) {
2701 if (IndexPos)
2702 IndexPos->push_back(Stream.GetCurrentBitNo());
2703 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2704 assert(N->isResolved() && "Expected forward references to be resolved");
2705
2706 switch (N->getMetadataID()) {
2707 default:
2708 llvm_unreachable("Invalid MDNode subclass");
2709#define HANDLE_MDNODE_LEAF(CLASS) \
2710 case Metadata::CLASS##Kind: \
2711 if (MDAbbrevs) \
2712 write##CLASS(cast<CLASS>(N), Record, \
2713 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2714 else \
2715 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2716 continue;
2717#include "llvm/IR/Metadata.def"
2718 }
2719 }
2720 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2722 continue;
2723 }
2724 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2725 }
2726}
2727
2728void ModuleBitcodeWriter::writeModuleMetadata() {
2729 if (!VE.hasMDs() && M.named_metadata_empty())
2730 return;
2731
2733 SmallVector<uint64_t, 64> Record;
2734
2735 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2736 // block and load any metadata.
2737 std::vector<unsigned> MDAbbrevs;
2738
2739 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2740 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2741 createDILocationAbbrev(/*WithIRLayers=*/false);
2742 DILocationLayersAbbrev = createDILocationAbbrev(/*WithIRLayers=*/true);
2743 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2744 createGenericDINodeAbbrev();
2745
2746 auto Abbv = std::make_shared<BitCodeAbbrev>();
2747 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2750 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2751
2752 Abbv = std::make_shared<BitCodeAbbrev>();
2753 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2754 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2755 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2756 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2757
2758 // Emit MDStrings together upfront.
2759 writeMetadataStrings(VE.getMDStrings(), Record);
2760
2761 // We only emit an index for the metadata record if we have more than a given
2762 // (naive) threshold of metadatas, otherwise it is not worth it.
2763 if (VE.getNonMDStrings().size() > IndexThreshold) {
2764 // Write a placeholder value in for the offset of the metadata index,
2765 // which is written after the records, so that it can include
2766 // the offset of each entry. The placeholder offset will be
2767 // updated after all records are emitted.
2768 uint64_t Vals[] = {0, 0};
2769 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2770 }
2771
2772 // Compute and save the bit offset to the current position, which will be
2773 // patched when we emit the index later. We can simply subtract the 64-bit
2774 // fixed size from the current bit number to get the location to backpatch.
2775 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2776
2777 // This index will contain the bitpos for each individual record.
2778 std::vector<uint64_t> IndexPos;
2779 IndexPos.reserve(VE.getNonMDStrings().size());
2780
2781 // Write all the records
2782 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2783
2784 if (VE.getNonMDStrings().size() > IndexThreshold) {
2785 // Now that we have emitted all the records we will emit the index. But
2786 // first
2787 // backpatch the forward reference so that the reader can skip the records
2788 // efficiently.
2789 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2790 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2791
2792 // Delta encode the index.
2793 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2794 for (auto &Elt : IndexPos) {
2795 auto EltDelta = Elt - PreviousValue;
2796 PreviousValue = Elt;
2797 Elt = EltDelta;
2798 }
2799 // Emit the index record.
2800 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2801 IndexPos.clear();
2802 }
2803
2804 // Write the named metadata now.
2805 writeNamedMetadata(Record);
2806
2807 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2808 SmallVector<uint64_t, 4> Record;
2809 Record.push_back(VE.getValueID(&GO));
2810 pushGlobalMetadataAttachment(Record, GO);
2812 };
2813 for (const Function &F : M)
2814 if (F.isDeclaration() && F.hasMetadata())
2815 AddDeclAttachedMetadata(F);
2816 for (const GlobalIFunc &GI : M.ifuncs())
2817 if (GI.hasMetadata())
2818 AddDeclAttachedMetadata(GI);
2819 // FIXME: Only store metadata for declarations here, and move data for global
2820 // variable definitions to a separate block (PR28134).
2821 for (const GlobalVariable &GV : M.globals())
2822 if (GV.hasMetadata())
2823 AddDeclAttachedMetadata(GV);
2824
2825 Stream.ExitBlock();
2826}
2827
2828void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2829 if (!VE.hasMDs())
2830 return;
2831
2833 // New block, new abbrev id space. Unlike the module block this one is not
2834 // randomly accessed, so the irlayers abbrev can be created on first use.
2835 DILocationLayersAbbrev = 0;
2836 SmallVector<uint64_t, 64> Record;
2837 writeMetadataStrings(VE.getMDStrings(), Record);
2838 writeMetadataRecords(VE.getNonMDStrings(), Record);
2839 Stream.ExitBlock();
2840}
2841
2842void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2843 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2844 // [n x [id, mdnode]]
2846 GO.getAllMetadata(MDs);
2847 for (const auto &I : MDs) {
2848 Record.push_back(I.first);
2849 Record.push_back(VE.getMetadataID(I.second));
2850 }
2851}
2852
2853void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2855
2856 SmallVector<uint64_t, 64> Record;
2857
2858 if (F.hasMetadata()) {
2859 pushGlobalMetadataAttachment(Record, F);
2860 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2861 Record.clear();
2862 }
2863
2864 // Write metadata attachments
2865 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2867 for (const BasicBlock &BB : F)
2868 for (const Instruction &I : BB) {
2869 MDs.clear();
2870 I.getAllMetadataOtherThanDebugLoc(MDs);
2871
2872 // If no metadata, ignore instruction.
2873 if (MDs.empty()) continue;
2874
2875 Record.push_back(VE.getInstructionID(&I));
2876
2877 for (const auto &[ID, MD] : MDs) {
2878 Record.push_back(ID);
2879 Record.push_back(VE.getMetadataID(MD));
2880 }
2881 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2882 Record.clear();
2883 }
2884
2885 Stream.ExitBlock();
2886}
2887
2888void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2889 SmallVector<uint64_t, 64> Record;
2890
2891 // Write metadata kinds
2892 // METADATA_KIND - [n x [id, name]]
2894 M.getMDKindNames(Names);
2895
2896 if (Names.empty()) return;
2897
2899
2900 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2901 Record.push_back(MDKindID);
2902 StringRef KName = Names[MDKindID];
2903 Record.append(KName.begin(), KName.end());
2904
2905 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2906 Record.clear();
2907 }
2908
2909 Stream.ExitBlock();
2910}
2911
2912void ModuleBitcodeWriter::writeOperandBundleTags() {
2913 // Write metadata kinds
2914 //
2915 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2916 //
2917 // OPERAND_BUNDLE_TAG - [strchr x N]
2918
2920 M.getOperandBundleTags(Tags);
2921
2922 if (Tags.empty())
2923 return;
2924
2926
2927 SmallVector<uint64_t, 64> Record;
2928
2929 for (auto Tag : Tags) {
2930 Record.append(Tag.begin(), Tag.end());
2931
2932 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2933 Record.clear();
2934 }
2935
2936 Stream.ExitBlock();
2937}
2938
2939void ModuleBitcodeWriter::writeSyncScopeNames() {
2941 M.getContext().getSyncScopeNames(SSNs);
2942 if (SSNs.empty())
2943 return;
2944
2946
2947 SmallVector<uint64_t, 64> Record;
2948 for (auto SSN : SSNs) {
2949 Record.append(SSN.begin(), SSN.end());
2950 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2951 Record.clear();
2952 }
2953
2954 Stream.ExitBlock();
2955}
2956
2957void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2958 bool isGlobal) {
2959 if (FirstVal == LastVal) return;
2960
2962
2963 unsigned AggregateAbbrev = 0;
2964 unsigned String8Abbrev = 0;
2965 unsigned CString7Abbrev = 0;
2966 unsigned CString6Abbrev = 0;
2967 // If this is a constant pool for the module, emit module-specific abbrevs.
2968 if (isGlobal) {
2969 // Abbrev for CST_CODE_AGGREGATE.
2970 auto Abbv = std::make_shared<BitCodeAbbrev>();
2971 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2974 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2975
2976 // Abbrev for CST_CODE_STRING.
2977 Abbv = std::make_shared<BitCodeAbbrev>();
2978 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2981 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2982 // Abbrev for CST_CODE_CSTRING.
2983 Abbv = std::make_shared<BitCodeAbbrev>();
2984 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2987 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2988 // Abbrev for CST_CODE_CSTRING.
2989 Abbv = std::make_shared<BitCodeAbbrev>();
2990 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2993 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2994 }
2995
2996 SmallVector<uint64_t, 64> Record;
2997
2998 const ValueEnumerator::ValueList &Vals = VE.getValues();
2999 Type *LastTy = nullptr;
3000 for (unsigned i = FirstVal; i != LastVal; ++i) {
3001 const Value *V = Vals[i].first;
3002 // If we need to switch types, do so now.
3003 if (V->getType() != LastTy) {
3004 LastTy = V->getType();
3005 Record.push_back(VE.getTypeID(LastTy));
3006 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
3007 CONSTANTS_SETTYPE_ABBREV);
3008 Record.clear();
3009 }
3010
3011 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
3012 Record.push_back(VE.getTypeID(IA->getFunctionType()));
3013 Record.push_back(
3014 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
3015 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
3016
3017 // Add the asm string.
3018 StringRef AsmStr = IA->getAsmString();
3019 Record.push_back(AsmStr.size());
3020 Record.append(AsmStr.begin(), AsmStr.end());
3021
3022 // Add the constraint string.
3023 StringRef ConstraintStr = IA->getConstraintString();
3024 Record.push_back(ConstraintStr.size());
3025 Record.append(ConstraintStr.begin(), ConstraintStr.end());
3026 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
3027 Record.clear();
3028 continue;
3029 }
3030 const Constant *C = cast<Constant>(V);
3031 unsigned Code = -1U;
3032 unsigned AbbrevToUse = 0;
3033 if (C->isNullValue()) {
3035 } else if (isa<PoisonValue>(C)) {
3037 } else if (isa<UndefValue>(C)) {
3039 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
3040 if (IV->getBitWidth() <= 64) {
3041 uint64_t V = IV->getSExtValue();
3042 emitSignedInt64(Record, V);
3044 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3045 } else { // Wide integers, > 64 bits in size.
3046 emitWideAPInt(Record, IV->getValue());
3048 }
3049 } else if (const ConstantByte *BV = dyn_cast<ConstantByte>(C)) {
3050 if (BV->getBitWidth() <= 64) {
3051 uint64_t V = BV->getSExtValue();
3052 emitSignedInt64(Record, V);
3054 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3055 } else { // Wide bytes, > 64 bits in size.
3056 emitWideAPInt(Record, BV->getValue());
3058 }
3059 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3061 Type *Ty = CFP->getType()->getScalarType();
3062 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
3063 Ty->isDoubleTy()) {
3064 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3065 } else if (Ty->isX86_FP80Ty()) {
3066 // api needed to prevent premature destruction
3067 // bits are not in the same order as a normal i80 APInt, compensate.
3068 APInt api = CFP->getValueAPF().bitcastToAPInt();
3069 const uint64_t *p = api.getRawData();
3070 Record.push_back((p[1] << 48) | (p[0] >> 16));
3071 Record.push_back(p[0] & 0xffffLL);
3072 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
3073 APInt api = CFP->getValueAPF().bitcastToAPInt();
3074 const uint64_t *p = api.getRawData();
3075 Record.push_back(p[0]);
3076 Record.push_back(p[1]);
3077 } else {
3078 assert(0 && "Unknown FP type!");
3079 }
3080 } else if (isa<ConstantDataSequential>(C) &&
3081 cast<ConstantDataSequential>(C)->isString()) {
3082 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
3083 // Emit constant strings specially.
3084 uint64_t NumElts = Str->getNumElements();
3085 // If this is a null-terminated string, use the denser CSTRING encoding.
3086 if (Str->isCString()) {
3088 --NumElts; // Don't encode the null, which isn't allowed by char6.
3089 } else {
3091 AbbrevToUse = String8Abbrev;
3092 }
3093 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
3094 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
3095 for (uint64_t i = 0; i != NumElts; ++i) {
3096 unsigned char V = Str->getElementAsInteger(i);
3097 Record.push_back(V);
3098 isCStr7 &= (V & 128) == 0;
3099 if (isCStrChar6)
3100 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
3101 }
3102
3103 if (isCStrChar6)
3104 AbbrevToUse = CString6Abbrev;
3105 else if (isCStr7)
3106 AbbrevToUse = CString7Abbrev;
3107 } else if (const ConstantDataSequential *CDS =
3110 Type *EltTy = CDS->getElementType();
3111 if (isa<IntegerType>(EltTy) || isa<ByteType>(EltTy)) {
3112 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3113 Record.push_back(CDS->getElementAsInteger(i));
3114 } else {
3115 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3116 Record.push_back(
3117 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3118 }
3119 } else if (isa<ConstantAggregate>(C)) {
3121 for (const Value *Op : C->operands())
3122 Record.push_back(VE.getValueID(Op));
3123 AbbrevToUse = AggregateAbbrev;
3124 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3125 switch (CE->getOpcode()) {
3126 default:
3127 if (Instruction::isCast(CE->getOpcode())) {
3129 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
3130 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3131 Record.push_back(VE.getValueID(C->getOperand(0)));
3132 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3133 } else {
3134 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
3136 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
3137 Record.push_back(VE.getValueID(C->getOperand(0)));
3138 Record.push_back(VE.getValueID(C->getOperand(1)));
3140 if (Flags != 0)
3141 Record.push_back(Flags);
3142 }
3143 break;
3144 case Instruction::GetElementPtr: {
3146 const auto *GO = cast<GEPOperator>(C);
3147 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
3148 Record.push_back(getOptimizationFlags(GO));
3149 if (std::optional<ConstantRange> Range = GO->getInRange()) {
3151 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
3152 }
3153 for (const Value *Op : CE->operands()) {
3154 Record.push_back(VE.getTypeID(Op->getType()));
3155 Record.push_back(VE.getValueID(Op));
3156 }
3157 break;
3158 }
3159 case Instruction::ExtractElement:
3161 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3162 Record.push_back(VE.getValueID(C->getOperand(0)));
3163 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
3164 Record.push_back(VE.getValueID(C->getOperand(1)));
3165 break;
3166 case Instruction::InsertElement:
3168 Record.push_back(VE.getValueID(C->getOperand(0)));
3169 Record.push_back(VE.getValueID(C->getOperand(1)));
3170 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
3171 Record.push_back(VE.getValueID(C->getOperand(2)));
3172 break;
3173 case Instruction::ShuffleVector:
3174 // If the return type and argument types are the same, this is a
3175 // standard shufflevector instruction. If the types are different,
3176 // then the shuffle is widening or truncating the input vectors, and
3177 // the argument type must also be encoded.
3178 if (C->getType() == C->getOperand(0)->getType()) {
3180 } else {
3182 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3183 }
3184 Record.push_back(VE.getValueID(C->getOperand(0)));
3185 Record.push_back(VE.getValueID(C->getOperand(1)));
3186 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
3187 break;
3188 }
3189 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
3191 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
3192 Record.push_back(VE.getValueID(BA->getFunction()));
3193 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
3194 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
3196 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
3197 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
3198 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
3200 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
3201 Record.push_back(VE.getValueID(NC->getGlobalValue()));
3202 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
3204 Record.push_back(VE.getValueID(CPA->getPointer()));
3205 Record.push_back(VE.getValueID(CPA->getKey()));
3206 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
3207 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
3208 Record.push_back(VE.getValueID(CPA->getDeactivationSymbol()));
3209 } else {
3210#ifndef NDEBUG
3211 C->dump();
3212#endif
3213 llvm_unreachable("Unknown constant!");
3214 }
3215 Stream.EmitRecord(Code, Record, AbbrevToUse);
3216 Record.clear();
3217 }
3218
3219 Stream.ExitBlock();
3220}
3221
3222void ModuleBitcodeWriter::writeModuleConstants() {
3223 const ValueEnumerator::ValueList &Vals = VE.getValues();
3224
3225 // Find the first constant to emit, which is the first non-globalvalue value.
3226 // We know globalvalues have been emitted by WriteModuleInfo.
3227 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
3228 if (!isa<GlobalValue>(Vals[i].first)) {
3229 writeConstants(i, Vals.size(), true);
3230 return;
3231 }
3232 }
3233}
3234
3235/// pushValueAndType - The file has to encode both the value and type id for
3236/// many values, because we need to know what type to create for forward
3237/// references. However, most operands are not forward references, so this type
3238/// field is not needed.
3239///
3240/// This function adds V's value ID to Vals. If the value ID is higher than the
3241/// instruction ID, then it is a forward reference, and it also includes the
3242/// type ID. The value ID that is written is encoded relative to the InstID.
3243bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
3244 SmallVectorImpl<unsigned> &Vals) {
3245 unsigned ValID = VE.getValueID(V);
3246 // Make encoding relative to the InstID.
3247 Vals.push_back(InstID - ValID);
3248 if (ValID >= InstID) {
3249 Vals.push_back(VE.getTypeID(V->getType()));
3250 return true;
3251 }
3252 return false;
3253}
3254
3255bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
3256 SmallVectorImpl<unsigned> &Vals) {
3257 bool IsMetadata = V->getType()->isMetadataTy();
3258 if (IsMetadata) {
3260 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
3261 unsigned ValID = VE.getMetadataID(MD);
3262 Vals.push_back(InstID - ValID);
3263 return false;
3264 }
3265 return pushValueAndType(V, InstID, Vals);
3266}
3267
3268void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
3269 unsigned InstID) {
3271 LLVMContext &C = CS.getContext();
3272
3273 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
3274 const auto &Bundle = CS.getOperandBundleAt(i);
3275 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
3276
3277 for (auto &Input : Bundle.Inputs)
3278 pushValueOrMetadata(Input, InstID, Record);
3279
3281 Record.clear();
3282 }
3283}
3284
3285/// pushValue - Like pushValueAndType, but where the type of the value is
3286/// omitted (perhaps it was already encoded in an earlier operand).
3287void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
3288 SmallVectorImpl<unsigned> &Vals) {
3289 unsigned ValID = VE.getValueID(V);
3290 Vals.push_back(InstID - ValID);
3291}
3292
3293void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
3294 SmallVectorImpl<uint64_t> &Vals) {
3295 unsigned ValID = VE.getValueID(V);
3296 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3297 emitSignedInt64(Vals, diff);
3298}
3299
3300/// WriteInstruction - Emit an instruction to the specified stream.
3301void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
3302 unsigned InstID,
3303 SmallVectorImpl<unsigned> &Vals) {
3304 unsigned Code = 0;
3305 unsigned AbbrevToUse = 0;
3306 VE.setInstructionID(&I);
3307 switch (I.getOpcode()) {
3308 default:
3309 if (Instruction::isCast(I.getOpcode())) {
3311 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3312 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3313 Vals.push_back(VE.getTypeID(I.getType()));
3314 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3316 if (Flags != 0) {
3317 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3318 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3319 Vals.push_back(Flags);
3320 }
3321 } else {
3322 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3324 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3325 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3326 pushValue(I.getOperand(1), InstID, Vals);
3327 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3329 if (Flags != 0) {
3330 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3331 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3332 Vals.push_back(Flags);
3333 }
3334 }
3335 break;
3336 case Instruction::FNeg: {
3338 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3339 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3340 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3342 if (Flags != 0) {
3343 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3344 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3345 Vals.push_back(Flags);
3346 }
3347 break;
3348 }
3349 case Instruction::GetElementPtr: {
3351 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3352 auto &GEPInst = cast<GetElementPtrInst>(I);
3354 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3355 for (const Value *Op : I.operands())
3356 pushValueAndType(Op, InstID, Vals);
3357 break;
3358 }
3359 case Instruction::ExtractValue: {
3361 pushValueAndType(I.getOperand(0), InstID, Vals);
3362 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3363 Vals.append(EVI->idx_begin(), EVI->idx_end());
3364 break;
3365 }
3366 case Instruction::InsertValue: {
3368 pushValueAndType(I.getOperand(0), InstID, Vals);
3369 pushValueAndType(I.getOperand(1), InstID, Vals);
3370 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3371 Vals.append(IVI->idx_begin(), IVI->idx_end());
3372 break;
3373 }
3374 case Instruction::Select: {
3376 pushValueAndType(I.getOperand(1), InstID, Vals);
3377 pushValue(I.getOperand(2), InstID, Vals);
3378 pushValueAndType(I.getOperand(0), InstID, Vals);
3380 if (Flags != 0)
3381 Vals.push_back(Flags);
3382 break;
3383 }
3384 case Instruction::ExtractElement:
3386 pushValueAndType(I.getOperand(0), InstID, Vals);
3387 pushValueAndType(I.getOperand(1), InstID, Vals);
3388 break;
3389 case Instruction::InsertElement:
3391 pushValueAndType(I.getOperand(0), InstID, Vals);
3392 pushValue(I.getOperand(1), InstID, Vals);
3393 pushValueAndType(I.getOperand(2), InstID, Vals);
3394 break;
3395 case Instruction::BitExtract:
3397 Vals.push_back(VE.getTypeID(I.getType()));
3398 pushValueAndType(I.getOperand(0), InstID, Vals);
3399 pushValueAndType(I.getOperand(1), InstID, Vals);
3400 break;
3401 case Instruction::BitInsert:
3403 pushValueAndType(I.getOperand(0), InstID, Vals);
3404 pushValueAndType(I.getOperand(1), InstID, Vals);
3405 pushValueAndType(I.getOperand(2), InstID, Vals);
3406 break;
3407 case Instruction::ShuffleVector:
3409 pushValueAndType(I.getOperand(0), InstID, Vals);
3410 pushValue(I.getOperand(1), InstID, Vals);
3411 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3412 Vals);
3413 break;
3414 case Instruction::ICmp:
3415 case Instruction::FCmp: {
3416 // compare returning Int1Ty or vector of Int1Ty
3418 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3419 if (pushValueAndType(I.getOperand(0), InstID, Vals))
3420 AbbrevToUse = 0;
3421 pushValue(I.getOperand(1), InstID, Vals);
3424 if (Flags != 0) {
3425 Vals.push_back(Flags);
3426 if (AbbrevToUse)
3427 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3428 }
3429 break;
3430 }
3431
3432 case Instruction::Ret:
3433 {
3435 unsigned NumOperands = I.getNumOperands();
3436 if (NumOperands == 0)
3437 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3438 else if (NumOperands == 1) {
3439 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3440 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3441 } else {
3442 for (const Value *Op : I.operands())
3443 pushValueAndType(Op, InstID, Vals);
3444 }
3445 }
3446 break;
3447 case Instruction::UncondBr: {
3449 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3450 const UncondBrInst &II = cast<UncondBrInst>(I);
3451 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3452 } break;
3453 case Instruction::CondBr: {
3455 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3456 const CondBrInst &II = cast<CondBrInst>(I);
3457 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3458 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3459 pushValue(II.getCondition(), InstID, Vals);
3460 } break;
3461 case Instruction::Switch:
3462 {
3464 const SwitchInst &SI = cast<SwitchInst>(I);
3465 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3466 pushValue(SI.getCondition(), InstID, Vals);
3467 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3468 for (auto Case : SI.cases()) {
3469 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3470 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3471 }
3472 }
3473 break;
3474 case Instruction::IndirectBr:
3476 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3477 // Encode the address operand as relative, but not the basic blocks.
3478 pushValue(I.getOperand(0), InstID, Vals);
3479 for (const Value *Op : drop_begin(I.operands()))
3480 Vals.push_back(VE.getValueID(Op));
3481 break;
3482
3483 case Instruction::Invoke: {
3484 const InvokeInst *II = cast<InvokeInst>(&I);
3485 const Value *Callee = II->getCalledOperand();
3486 FunctionType *FTy = II->getFunctionType();
3487
3488 if (II->hasOperandBundles())
3489 writeOperandBundles(*II, InstID);
3490
3492
3493 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3494 Vals.push_back(II->getCallingConv() | 1 << 13);
3495 Vals.push_back(VE.getValueID(II->getNormalDest()));
3496 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3497 Vals.push_back(VE.getTypeID(FTy));
3498 pushValueAndType(Callee, InstID, Vals);
3499
3500 // Emit value #'s for the fixed parameters.
3501 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3502 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3503
3504 // Emit type/value pairs for varargs params.
3505 if (FTy->isVarArg()) {
3506 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3507 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3508 }
3509 break;
3510 }
3511 case Instruction::Resume:
3513 pushValueAndType(I.getOperand(0), InstID, Vals);
3514 break;
3515 case Instruction::CleanupRet: {
3517 const auto &CRI = cast<CleanupReturnInst>(I);
3518 pushValue(CRI.getCleanupPad(), InstID, Vals);
3519 if (CRI.hasUnwindDest())
3520 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3521 break;
3522 }
3523 case Instruction::CatchRet: {
3525 const auto &CRI = cast<CatchReturnInst>(I);
3526 pushValue(CRI.getCatchPad(), InstID, Vals);
3527 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3528 break;
3529 }
3530 case Instruction::CleanupPad:
3531 case Instruction::CatchPad: {
3532 const auto &FuncletPad = cast<FuncletPadInst>(I);
3535 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3536
3537 unsigned NumArgOperands = FuncletPad.arg_size();
3538 Vals.push_back(NumArgOperands);
3539 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3540 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3541 break;
3542 }
3543 case Instruction::CatchSwitch: {
3545 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3546
3547 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3548
3549 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3550 Vals.push_back(NumHandlers);
3551 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3552 Vals.push_back(VE.getValueID(CatchPadBB));
3553
3554 if (CatchSwitch.hasUnwindDest())
3555 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3556 break;
3557 }
3558 case Instruction::CallBr: {
3559 const CallBrInst *CBI = cast<CallBrInst>(&I);
3560 const Value *Callee = CBI->getCalledOperand();
3561 FunctionType *FTy = CBI->getFunctionType();
3562
3563 if (CBI->hasOperandBundles())
3564 writeOperandBundles(*CBI, InstID);
3565
3567
3569
3572
3573 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3574 Vals.push_back(CBI->getNumIndirectDests());
3575 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3576 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3577
3578 Vals.push_back(VE.getTypeID(FTy));
3579 pushValueAndType(Callee, InstID, Vals);
3580
3581 // Emit value #'s for the fixed parameters.
3582 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3583 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3584
3585 // Emit type/value pairs for varargs params.
3586 if (FTy->isVarArg()) {
3587 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3588 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3589 }
3590 break;
3591 }
3592 case Instruction::Unreachable:
3594 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3595 break;
3596
3597 case Instruction::PHI: {
3598 const PHINode &PN = cast<PHINode>(I);
3600 // With the newer instruction encoding, forward references could give
3601 // negative valued IDs. This is most common for PHIs, so we use
3602 // signed VBRs.
3604 Vals64.push_back(VE.getTypeID(PN.getType()));
3605 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3606 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3607 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3608 }
3609
3611 if (Flags != 0)
3612 Vals64.push_back(Flags);
3613
3614 // Emit a Vals64 vector and exit.
3615 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3616 Vals64.clear();
3617 return;
3618 }
3619
3620 case Instruction::LandingPad: {
3621 const LandingPadInst &LP = cast<LandingPadInst>(I);
3623 Vals.push_back(VE.getTypeID(LP.getType()));
3624 Vals.push_back(LP.isCleanup());
3625 Vals.push_back(LP.getNumClauses());
3626 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3627 if (LP.isCatch(I))
3629 else
3631 pushValueAndType(LP.getClause(I), InstID, Vals);
3632 }
3633 break;
3634 }
3635
3636 case Instruction::Alloca: {
3638 const AllocaInst &AI = cast<AllocaInst>(I);
3639 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3640 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3641 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3642 using APV = AllocaPackedValues;
3643 unsigned Record = 0;
3644 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3646 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3648 EncodedAlign >> APV::AlignLower::Bits);
3652 Vals.push_back(Record);
3653
3654 unsigned AS = AI.getAddressSpace();
3655 if (AS != M.getDataLayout().getAllocaAddrSpace())
3656 Vals.push_back(AS);
3657 break;
3658 }
3659
3660 case Instruction::Load: {
3661 const auto &LI = cast<LoadInst>(I);
3662 if (LI.isAtomic()) {
3664 pushValueAndType(LI.getOperand(0), InstID, Vals);
3665 } else {
3667 if (!pushValueAndType(LI.getOperand(0), InstID, Vals)) // ptr
3668 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3669 }
3670 Vals.push_back(VE.getTypeID(LI.getType()));
3671 Vals.push_back(getEncodedAlign(LI.getAlign()));
3672 Vals.push_back(LI.isVolatile());
3673 if (LI.isAtomic()) {
3674 Vals.push_back(getEncodedOrdering(LI.getOrdering()));
3675 Vals.push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3676 if (LI.isElementwise())
3677 Vals.push_back(1);
3678 }
3679 break;
3680 }
3681
3682 case Instruction::Store: {
3683 const auto &SI = cast<StoreInst>(I);
3684 if (SI.isAtomic()) {
3686 } else {
3688 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3689 }
3690 if (pushValueAndType(I.getOperand(1), InstID, Vals)) // ptrty + ptr
3691 AbbrevToUse = 0;
3692 if (pushValueAndType(I.getOperand(0), InstID, Vals)) // valty + val
3693 AbbrevToUse = 0;
3694 Vals.push_back(getEncodedAlign(SI.getAlign()));
3695 Vals.push_back(SI.isVolatile());
3696 if (SI.isAtomic()) {
3697 Vals.push_back(getEncodedOrdering(SI.getOrdering()));
3698 Vals.push_back(getEncodedSyncScopeID(SI.getSyncScopeID()));
3699 if (SI.isElementwise())
3700 Vals.push_back(1);
3701 }
3702 break;
3703 }
3704
3705 case Instruction::AtomicCmpXchg:
3707 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3708 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3709 pushValue(I.getOperand(2), InstID, Vals); // newval.
3710 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3711 Vals.push_back(
3712 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3713 Vals.push_back(
3714 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3715 Vals.push_back(
3716 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3717 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3718 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3719 break;
3720 case Instruction::AtomicRMW:
3722 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3723 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3725 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3726 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3727 Vals.push_back(
3728 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3729 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3730 break;
3731 case Instruction::Fence:
3733 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3734 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3735 break;
3736 case Instruction::Call: {
3737 const CallInst &CI = cast<CallInst>(I);
3738 FunctionType *FTy = CI.getFunctionType();
3739
3740 if (CI.hasOperandBundles())
3741 writeOperandBundles(CI, InstID);
3742
3744
3746
3747 unsigned Flags = getOptimizationFlags(&I);
3749 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3750 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3752 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3753 unsigned(Flags != 0) << bitc::CALL_FMF);
3754 if (Flags != 0)
3755 Vals.push_back(Flags);
3756
3757 Vals.push_back(VE.getTypeID(FTy));
3758 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3759
3760 // Emit value #'s for the fixed parameters.
3761 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3762 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3763
3764 // Emit type/value pairs for varargs params.
3765 if (FTy->isVarArg()) {
3766 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3767 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3768 }
3769 break;
3770 }
3771 case Instruction::VAArg:
3773 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3774 pushValue(I.getOperand(0), InstID, Vals); // valist.
3775 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3776 break;
3777 case Instruction::Freeze:
3779 pushValueAndType(I.getOperand(0), InstID, Vals);
3780 break;
3781 }
3782
3783 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3784 Vals.clear();
3785}
3786
3787/// Write a GlobalValue VST to the module. The purpose of this data structure is
3788/// to allow clients to efficiently find the function body.
3789void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3790 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3791 // Get the offset of the VST we are writing, and backpatch it into
3792 // the VST forward declaration record.
3793 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3794 // The BitcodeStartBit was the stream offset of the identification block.
3795 VSTOffset -= bitcodeStartBit();
3796 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3797 // Note that we add 1 here because the offset is relative to one word
3798 // before the start of the identification block, which was historically
3799 // always the start of the regular bitcode header.
3800 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3801
3803
3804 auto Abbv = std::make_shared<BitCodeAbbrev>();
3805 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3808 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3809
3810 for (const Function &F : M) {
3811 uint64_t Record[2];
3812
3813 if (F.isDeclaration())
3814 continue;
3815
3816 Record[0] = VE.getValueID(&F);
3817
3818 // Save the word offset of the function (from the start of the
3819 // actual bitcode written to the stream).
3820 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3821 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3822 // Note that we add 1 here because the offset is relative to one word
3823 // before the start of the identification block, which was historically
3824 // always the start of the regular bitcode header.
3825 Record[1] = BitcodeIndex / 32 + 1;
3826
3827 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3828 }
3829
3830 Stream.ExitBlock();
3831}
3832
3833/// Emit names for arguments, instructions and basic blocks in a function.
3834void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3835 const ValueSymbolTable &VST) {
3836 if (VST.empty())
3837 return;
3838
3840
3841 // FIXME: Set up the abbrev, we know how many values there are!
3842 // FIXME: We know if the type names can use 7-bit ascii.
3843 SmallVector<uint64_t, 64> NameVals;
3844
3845 for (const ValueName &Name : VST) {
3846 // Figure out the encoding to use for the name.
3848
3849 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3850 NameVals.push_back(VE.getValueID(Name.getValue()));
3851
3852 // VST_CODE_ENTRY: [valueid, namechar x N]
3853 // VST_CODE_BBENTRY: [bbid, namechar x N]
3854 unsigned Code;
3855 if (isa<BasicBlock>(Name.getValue())) {
3857 if (Bits == SE_Char6)
3858 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3859 } else {
3861 if (Bits == SE_Char6)
3862 AbbrevToUse = VST_ENTRY_6_ABBREV;
3863 else if (Bits == SE_Fixed7)
3864 AbbrevToUse = VST_ENTRY_7_ABBREV;
3865 }
3866
3867 for (const auto P : Name.getKey())
3868 NameVals.push_back((unsigned char)P);
3869
3870 // Emit the finished record.
3871 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3872 NameVals.clear();
3873 }
3874
3875 Stream.ExitBlock();
3876}
3877
3878void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3879 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3880 unsigned Code;
3881 if (isa<BasicBlock>(Order.V))
3883 else
3885
3886 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3887 Record.push_back(VE.getValueID(Order.V));
3888 Stream.EmitRecord(Code, Record);
3889}
3890
3891void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3893 "Expected to be preserving use-list order");
3894
3895 auto hasMore = [&]() {
3896 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3897 };
3898 if (!hasMore())
3899 // Nothing to do.
3900 return;
3901
3903 while (hasMore()) {
3904 writeUseList(std::move(VE.UseListOrders.back()));
3905 VE.UseListOrders.pop_back();
3906 }
3907 Stream.ExitBlock();
3908}
3909
3910/// Emit a function body to the module stream.
3911void ModuleBitcodeWriter::writeFunction(
3912 const Function &F,
3913 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3914 // Save the bitcode index of the start of this function block for recording
3915 // in the VST.
3916 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3917
3920
3922
3923 // Emit the number of basic blocks, so the reader can create them ahead of
3924 // time.
3925 Vals.push_back(VE.getBasicBlocks().size());
3927 Vals.clear();
3928
3929 // If there are function-local constants, emit them now.
3930 unsigned CstStart, CstEnd;
3931 VE.getFunctionConstantRange(CstStart, CstEnd);
3932 writeConstants(CstStart, CstEnd, false);
3933
3934 // If there is function-local metadata, emit it now.
3935 writeFunctionMetadata(F);
3936
3937 // Keep a running idea of what the instruction ID is.
3938 unsigned InstID = CstEnd;
3939
3940 bool NeedsMetadataAttachment = F.hasMetadata();
3941
3942 DILocation *LastDL = nullptr;
3943 SmallSetVector<Function *, 4> BlockAddressUsers;
3944
3945 // Finally, emit all the instructions, in order.
3946 for (const BasicBlock &BB : F) {
3947 for (const Instruction &I : BB) {
3948 writeInstruction(I, InstID, Vals);
3949
3950 if (!I.getType()->isVoidTy())
3951 ++InstID;
3952
3953 // If the instruction has metadata, write a metadata attachment later.
3954 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3955
3956 // If the instruction has a debug location, emit it.
3957 if (DILocation *DL = I.getDebugLoc()) {
3958 if (DL == LastDL) {
3959 // Just repeat the same debug loc as last time.
3961 } else {
3962 Vals.push_back(DL->getLine());
3963 Vals.push_back(DL->getColumn());
3964 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3965 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3966 Vals.push_back(DL->isImplicitCode());
3967 Vals.push_back(DL->getAtomGroup());
3968 Vals.push_back(DL->getAtomRank());
3969
3970 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3971 if (DILayerLocList *IRLayers = DL->getIRLayers()) {
3972 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3973 Vals.push_back(VE.getMetadataOrNullID(IRLayers));
3974 }
3975
3976 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals, DLAbbrev);
3977 Vals.clear();
3978 LastDL = DL;
3979 }
3980 }
3981
3982 // If the instruction has DbgRecords attached to it, emit them. Note that
3983 // they come after the instruction so that it's easy to attach them again
3984 // when reading the bitcode, even though conceptually the debug locations
3985 // start "before" the instruction.
3986 if (I.hasDbgRecords()) {
3987 /// Try to push the value only (unwrapped), otherwise push the
3988 /// metadata wrapped value. Returns true if the value was pushed
3989 /// without the ValueAsMetadata wrapper.
3990 auto PushValueOrMetadata = [&Vals, InstID,
3991 this](Metadata *RawLocation) {
3992 assert(RawLocation &&
3993 "RawLocation unexpectedly null in DbgVariableRecord");
3994 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3995 SmallVector<unsigned, 2> ValAndType;
3996 // If the value is a fwd-ref the type is also pushed. We don't
3997 // want the type, so fwd-refs are kept wrapped (pushValueAndType
3998 // returns false if the value is pushed without type).
3999 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4000 Vals.push_back(ValAndType[0]);
4001 return true;
4002 }
4003 }
4004 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
4005 // fwd-ref. Push the metadata ID.
4006 Vals.push_back(VE.getMetadataID(RawLocation));
4007 return false;
4008 };
4009
4010 // Write out non-instruction debug information attached to this
4011 // instruction. Write it after the instruction so that it's easy to
4012 // re-attach to the instruction reading the records in.
4013 for (DbgRecord &DR : I.getDbgMarker()->getDbgRecordRange()) {
4014 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
4015 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
4016 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
4018 Vals.clear();
4019 continue;
4020 }
4021
4022 // First 3 fields are common to all kinds:
4023 // DILocation, DILocalVariable, DIExpression
4024 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
4025 // ..., LocationMetadata
4026 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
4027 // ..., Value
4028 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
4029 // ..., LocationMetadata
4030 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
4031 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
4032 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
4033 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
4034 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
4035 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
4036 if (DVR.isDbgValue()) {
4037 if (PushValueOrMetadata(DVR.getRawLocation()))
4039 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4040 else
4042 } else if (DVR.isDbgDeclare()) {
4043 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4045 } else if (DVR.isDbgDeclareValue()) {
4046 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4048 } else {
4049 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
4050 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4051 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
4053 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
4055 }
4056 Vals.clear();
4057 }
4058 }
4059 }
4060
4061 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
4062 SmallVector<Value *> Worklist{BA};
4063 SmallPtrSet<Value *, 8> Visited{BA};
4064 while (!Worklist.empty()) {
4065 Value *V = Worklist.pop_back_val();
4066 for (User *U : V->users()) {
4067 if (auto *I = dyn_cast<Instruction>(U)) {
4068 Function *P = I->getFunction();
4069 if (P != &F)
4070 BlockAddressUsers.insert(P);
4071 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
4072 Visited.insert(U).second)
4073 Worklist.push_back(U);
4074 }
4075 }
4076 }
4077 }
4078
4079 if (!BlockAddressUsers.empty()) {
4080 Vals.resize(BlockAddressUsers.size());
4081 for (auto I : llvm::enumerate(BlockAddressUsers))
4082 Vals[I.index()] = VE.getValueID(I.value());
4084 Vals.clear();
4085 }
4086
4087 // Emit names for all the instructions etc.
4088 if (auto *Symtab = F.getValueSymbolTable())
4089 writeFunctionLevelValueSymbolTable(*Symtab);
4090
4091 if (NeedsMetadataAttachment)
4092 writeFunctionMetadataAttachment(F);
4094 writeUseListBlock(&F);
4095 VE.purgeFunction();
4096 Stream.ExitBlock();
4097}
4098
4099// Emit blockinfo, which defines the standard abbreviations etc.
4100void ModuleBitcodeWriter::writeBlockInfo() {
4101 // We only want to emit block info records for blocks that have multiple
4102 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
4103 // Other blocks can define their abbrevs inline.
4104 Stream.EnterBlockInfoBlock();
4105
4106 // Encode type indices using fixed size based on number of types.
4107 BitCodeAbbrevOp TypeAbbrevOp(BitCodeAbbrevOp::Fixed,
4109 // Encode value indices as 6-bit VBR.
4110 BitCodeAbbrevOp ValAbbrevOp(BitCodeAbbrevOp::VBR, 6);
4111
4112 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
4113 auto Abbv = std::make_shared<BitCodeAbbrev>();
4114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
4115 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4116 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4117 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4119 VST_ENTRY_8_ABBREV)
4120 llvm_unreachable("Unexpected abbrev ordering!");
4121 }
4122
4123 { // 7-bit fixed width VST_CODE_ENTRY strings.
4124 auto Abbv = std::make_shared<BitCodeAbbrev>();
4125 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4130 VST_ENTRY_7_ABBREV)
4131 llvm_unreachable("Unexpected abbrev ordering!");
4132 }
4133 { // 6-bit char6 VST_CODE_ENTRY strings.
4134 auto Abbv = std::make_shared<BitCodeAbbrev>();
4135 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4140 VST_ENTRY_6_ABBREV)
4141 llvm_unreachable("Unexpected abbrev ordering!");
4142 }
4143 { // 6-bit char6 VST_CODE_BBENTRY strings.
4144 auto Abbv = std::make_shared<BitCodeAbbrev>();
4145 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
4146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4150 VST_BBENTRY_6_ABBREV)
4151 llvm_unreachable("Unexpected abbrev ordering!");
4152 }
4153
4154 { // SETTYPE abbrev for CONSTANTS_BLOCK.
4155 auto Abbv = std::make_shared<BitCodeAbbrev>();
4156 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
4157 Abbv->Add(TypeAbbrevOp);
4159 CONSTANTS_SETTYPE_ABBREV)
4160 llvm_unreachable("Unexpected abbrev ordering!");
4161 }
4162
4163 { // INTEGER abbrev for CONSTANTS_BLOCK.
4164 auto Abbv = std::make_shared<BitCodeAbbrev>();
4165 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
4166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4168 CONSTANTS_INTEGER_ABBREV)
4169 llvm_unreachable("Unexpected abbrev ordering!");
4170 }
4171
4172 { // BYTE abbrev for CONSTANTS_BLOCK.
4173 auto Abbv = std::make_shared<BitCodeAbbrev>();
4174 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_BYTE));
4175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4177 CONSTANTS_BYTE_ABBREV)
4178 llvm_unreachable("Unexpected abbrev ordering!");
4179 }
4180
4181 { // CE_CAST abbrev for CONSTANTS_BLOCK.
4182 auto Abbv = std::make_shared<BitCodeAbbrev>();
4183 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
4184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
4185 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
4187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
4188
4190 CONSTANTS_CE_CAST_Abbrev)
4191 llvm_unreachable("Unexpected abbrev ordering!");
4192 }
4193 { // NULL abbrev for CONSTANTS_BLOCK.
4194 auto Abbv = std::make_shared<BitCodeAbbrev>();
4195 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
4197 CONSTANTS_NULL_Abbrev)
4198 llvm_unreachable("Unexpected abbrev ordering!");
4199 }
4200
4201 // FIXME: This should only use space for first class types!
4202
4203 { // INST_LOAD abbrev for FUNCTION_BLOCK.
4204 auto Abbv = std::make_shared<BitCodeAbbrev>();
4205 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
4206 Abbv->Add(ValAbbrevOp); // Ptr
4207 Abbv->Add(TypeAbbrevOp); // dest ty
4208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
4209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4210 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4211 FUNCTION_INST_LOAD_ABBREV)
4212 llvm_unreachable("Unexpected abbrev ordering!");
4213 }
4214 {
4215 auto Abbv = std::make_shared<BitCodeAbbrev>();
4216 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_STORE));
4217 Abbv->Add(ValAbbrevOp); // op1
4218 Abbv->Add(ValAbbrevOp); // op0
4219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // align
4220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4221 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4222 FUNCTION_INST_STORE_ABBREV)
4223 llvm_unreachable("Unexpected abbrev ordering!");
4224 }
4225 { // INST_UNOP abbrev for FUNCTION_BLOCK.
4226 auto Abbv = std::make_shared<BitCodeAbbrev>();
4227 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4228 Abbv->Add(ValAbbrevOp); // LHS
4229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4230 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4231 FUNCTION_INST_UNOP_ABBREV)
4232 llvm_unreachable("Unexpected abbrev ordering!");
4233 }
4234 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
4235 auto Abbv = std::make_shared<BitCodeAbbrev>();
4236 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4237 Abbv->Add(ValAbbrevOp); // LHS
4238 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4239 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4240 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4241 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4242 llvm_unreachable("Unexpected abbrev ordering!");
4243 }
4244 { // INST_BINOP abbrev for FUNCTION_BLOCK.
4245 auto Abbv = std::make_shared<BitCodeAbbrev>();
4246 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4247 Abbv->Add(ValAbbrevOp); // LHS
4248 Abbv->Add(ValAbbrevOp); // RHS
4249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4250 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4251 FUNCTION_INST_BINOP_ABBREV)
4252 llvm_unreachable("Unexpected abbrev ordering!");
4253 }
4254 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
4255 auto Abbv = std::make_shared<BitCodeAbbrev>();
4256 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4257 Abbv->Add(ValAbbrevOp); // LHS
4258 Abbv->Add(ValAbbrevOp); // RHS
4259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4261 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4262 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4263 llvm_unreachable("Unexpected abbrev ordering!");
4264 }
4265 { // INST_CAST abbrev for FUNCTION_BLOCK.
4266 auto Abbv = std::make_shared<BitCodeAbbrev>();
4267 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4268 Abbv->Add(ValAbbrevOp); // OpVal
4269 Abbv->Add(TypeAbbrevOp); // dest ty
4270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4271 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4272 FUNCTION_INST_CAST_ABBREV)
4273 llvm_unreachable("Unexpected abbrev ordering!");
4274 }
4275 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
4276 auto Abbv = std::make_shared<BitCodeAbbrev>();
4277 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4278 Abbv->Add(ValAbbrevOp); // OpVal
4279 Abbv->Add(TypeAbbrevOp); // dest ty
4280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 9)); // flags
4282 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4283 FUNCTION_INST_CAST_FLAGS_ABBREV)
4284 llvm_unreachable("Unexpected abbrev ordering!");
4285 }
4286
4287 { // INST_RET abbrev for FUNCTION_BLOCK.
4288 auto Abbv = std::make_shared<BitCodeAbbrev>();
4289 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4290 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4291 FUNCTION_INST_RET_VOID_ABBREV)
4292 llvm_unreachable("Unexpected abbrev ordering!");
4293 }
4294 { // INST_RET abbrev for FUNCTION_BLOCK.
4295 auto Abbv = std::make_shared<BitCodeAbbrev>();
4296 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4297 Abbv->Add(ValAbbrevOp);
4298 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4299 FUNCTION_INST_RET_VAL_ABBREV)
4300 llvm_unreachable("Unexpected abbrev ordering!");
4301 }
4302 {
4303 auto Abbv = std::make_shared<BitCodeAbbrev>();
4304 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4305 // TODO: Use different abbrev for absolute value reference (succ0)?
4306 Abbv->Add(ValAbbrevOp); // succ0
4307 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4308 FUNCTION_INST_BR_UNCOND_ABBREV)
4309 llvm_unreachable("Unexpected abbrev ordering!");
4310 }
4311 {
4312 auto Abbv = std::make_shared<BitCodeAbbrev>();
4313 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4314 // TODO: Use different abbrev for absolute value references (succ0, succ1)?
4315 Abbv->Add(ValAbbrevOp); // succ0
4316 Abbv->Add(ValAbbrevOp); // succ1
4317 Abbv->Add(ValAbbrevOp); // cond
4318 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4319 FUNCTION_INST_BR_COND_ABBREV)
4320 llvm_unreachable("Unexpected abbrev ordering!");
4321 }
4322 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
4323 auto Abbv = std::make_shared<BitCodeAbbrev>();
4324 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
4325 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4326 FUNCTION_INST_UNREACHABLE_ABBREV)
4327 llvm_unreachable("Unexpected abbrev ordering!");
4328 }
4329 {
4330 auto Abbv = std::make_shared<BitCodeAbbrev>();
4331 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
4332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // flags
4333 Abbv->Add(TypeAbbrevOp); // dest ty
4334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4335 Abbv->Add(ValAbbrevOp);
4336 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4337 FUNCTION_INST_GEP_ABBREV)
4338 llvm_unreachable("Unexpected abbrev ordering!");
4339 }
4340 {
4341 auto Abbv = std::make_shared<BitCodeAbbrev>();
4342 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4343 Abbv->Add(ValAbbrevOp); // op0
4344 Abbv->Add(ValAbbrevOp); // op1
4345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4346 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4347 FUNCTION_INST_CMP_ABBREV)
4348 llvm_unreachable("Unexpected abbrev ordering!");
4349 }
4350 {
4351 auto Abbv = std::make_shared<BitCodeAbbrev>();
4352 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4353 Abbv->Add(ValAbbrevOp); // op0
4354 Abbv->Add(ValAbbrevOp); // op1
4355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4357 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4358 FUNCTION_INST_CMP_FLAGS_ABBREV)
4359 llvm_unreachable("Unexpected abbrev ordering!");
4360 }
4361 {
4362 auto Abbv = std::make_shared<BitCodeAbbrev>();
4363 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
4364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
4365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
4366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
4367 Abbv->Add(ValAbbrevOp); // val
4368 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4369 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4370 llvm_unreachable("Unexpected abbrev ordering! 1");
4371 }
4372 {
4373 auto Abbv = std::make_shared<BitCodeAbbrev>();
4374 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4375 // NOTE: No IsDistinct field for FUNC_CODE_DEBUG_LOC.
4376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4383 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4384 FUNCTION_DEBUG_LOC_ABBREV)
4385 llvm_unreachable("Unexpected abbrev ordering!");
4386 }
4387 { // DEBUG_LOC abbrev for FUNCTION_BLOCK, irlayers variant.
4388 // Separate abbrev so a location without layers does not spend a VBR chunk
4389 // encoding a zero; writeInstruction picks between the two per record.
4390 auto Abbv = std::make_shared<BitCodeAbbrev>();
4391 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4392 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4393 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4394 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // irlayers.
4400 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4401 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4402 llvm_unreachable("Unexpected abbrev ordering!");
4403 }
4404 Stream.ExitBlock();
4405}
4406
4407/// Write the module path strings, currently only used when generating
4408/// a combined index file.
4409void IndexBitcodeWriter::writeModStrings() {
4411
4412 // TODO: See which abbrev sizes we actually need to emit
4413
4414 // 8-bit fixed-width MST_ENTRY strings.
4415 auto Abbv = std::make_shared<BitCodeAbbrev>();
4416 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4418 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4420 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
4421
4422 // 7-bit fixed width MST_ENTRY strings.
4423 Abbv = std::make_shared<BitCodeAbbrev>();
4424 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4425 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4426 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4427 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4428 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
4429
4430 // 6-bit char6 MST_ENTRY strings.
4431 Abbv = std::make_shared<BitCodeAbbrev>();
4432 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4436 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
4437
4438 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4439 Abbv = std::make_shared<BitCodeAbbrev>();
4440 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
4441 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4446 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4447
4449 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4450 StringRef Key = MPSE.getKey();
4451 const auto &Hash = MPSE.getValue();
4453 unsigned AbbrevToUse = Abbrev8Bit;
4454 if (Bits == SE_Char6)
4455 AbbrevToUse = Abbrev6Bit;
4456 else if (Bits == SE_Fixed7)
4457 AbbrevToUse = Abbrev7Bit;
4458
4459 auto ModuleId = ModuleIdMap.size();
4460 ModuleIdMap[Key] = ModuleId;
4461 Vals.push_back(ModuleId);
4462 // Use bytes_begin/end() for unsigned char iteration.
4463 Vals.append(Key.bytes_begin(), Key.bytes_end());
4464
4465 // Emit the finished record.
4466 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4467
4468 // Emit an optional hash for the module now
4469 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4470 Vals.assign(Hash.begin(), Hash.end());
4471 // Emit the hash record.
4472 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4473 }
4474
4475 Vals.clear();
4476 });
4477 Stream.ExitBlock();
4478}
4479
4480/// Write the function type metadata related records that need to appear before
4481/// a function summary entry (whether per-module or combined).
4482template <typename Fn>
4484 FunctionSummary *FS,
4485 Fn GetValueID) {
4486 if (!FS->type_tests().empty())
4487 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4488
4490
4491 auto WriteVFuncIdVec = [&](uint64_t Ty,
4493 if (VFs.empty())
4494 return;
4495 Record.clear();
4496 for (auto &VF : VFs) {
4497 Record.push_back(VF.GUID);
4498 Record.push_back(VF.Offset);
4499 }
4500 Stream.EmitRecord(Ty, Record);
4501 };
4502
4503 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4504 FS->type_test_assume_vcalls());
4505 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4506 FS->type_checked_load_vcalls());
4507
4508 auto WriteConstVCallVec = [&](uint64_t Ty,
4510 for (auto &VC : VCs) {
4511 Record.clear();
4512 Record.push_back(VC.VFunc.GUID);
4513 Record.push_back(VC.VFunc.Offset);
4514 llvm::append_range(Record, VC.Args);
4515 Stream.EmitRecord(Ty, Record);
4516 }
4517 };
4518
4519 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4520 FS->type_test_assume_const_vcalls());
4521 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4522 FS->type_checked_load_const_vcalls());
4523
4524 auto WriteRange = [&](ConstantRange Range) {
4526 assert(Range.getLower().getNumWords() == 1);
4527 assert(Range.getUpper().getNumWords() == 1);
4528 emitSignedInt64(Record, *Range.getLower().getRawData());
4529 emitSignedInt64(Record, *Range.getUpper().getRawData());
4530 };
4531
4532 if (!FS->paramAccesses().empty()) {
4533 Record.clear();
4534 for (auto &Arg : FS->paramAccesses()) {
4535 size_t UndoSize = Record.size();
4536 Record.push_back(Arg.ParamNo);
4537 WriteRange(Arg.Use);
4538 Record.push_back(Arg.Calls.size());
4539 for (auto &Call : Arg.Calls) {
4540 Record.push_back(Call.ParamNo);
4541 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4542 if (!ValueID) {
4543 // If ValueID is unknown we can't drop just this call, we must drop
4544 // entire parameter.
4545 Record.resize(UndoSize);
4546 break;
4547 }
4548 Record.push_back(*ValueID);
4549 WriteRange(Call.Offsets);
4550 }
4551 }
4552 if (!Record.empty())
4554 }
4555}
4556
4557/// Collect type IDs from type tests used by function.
4558static void
4560 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4561 if (!FS->type_tests().empty())
4562 for (auto &TT : FS->type_tests())
4563 ReferencedTypeIds.insert(TT);
4564
4565 auto GetReferencedTypesFromVFuncIdVec =
4567 for (auto &VF : VFs)
4568 ReferencedTypeIds.insert(VF.GUID);
4569 };
4570
4571 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4572 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4573
4574 auto GetReferencedTypesFromConstVCallVec =
4576 for (auto &VC : VCs)
4577 ReferencedTypeIds.insert(VC.VFunc.GUID);
4578 };
4579
4580 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4581 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4582}
4583
4585 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4587 NameVals.push_back(args.size());
4588 llvm::append_range(NameVals, args);
4589
4590 NameVals.push_back(ByArg.TheKind);
4591 NameVals.push_back(ByArg.Info);
4592 NameVals.push_back(ByArg.Byte);
4593 NameVals.push_back(ByArg.Bit);
4594}
4595
4597 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4598 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4599 NameVals.push_back(Id);
4600
4601 NameVals.push_back(Wpd.TheKind);
4602 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4603 NameVals.push_back(Wpd.SingleImplName.size());
4604
4605 NameVals.push_back(Wpd.ResByArg.size());
4606 for (auto &A : Wpd.ResByArg)
4607 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4608}
4609
4611 StringTableBuilder &StrtabBuilder,
4612 StringRef Id,
4613 const TypeIdSummary &Summary) {
4614 NameVals.push_back(StrtabBuilder.add(Id));
4615 NameVals.push_back(Id.size());
4616
4617 NameVals.push_back(Summary.TTRes.TheKind);
4618 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4619 NameVals.push_back(Summary.TTRes.AlignLog2);
4620 NameVals.push_back(Summary.TTRes.SizeM1);
4621 NameVals.push_back(Summary.TTRes.BitMask);
4622 NameVals.push_back(Summary.TTRes.InlineBits);
4623
4624 for (auto &W : Summary.WPDRes)
4625 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4626 W.second);
4627}
4628
4630 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4631 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4633 NameVals.push_back(StrtabBuilder.add(Id));
4634 NameVals.push_back(Id.size());
4635
4636 for (auto &P : Summary) {
4637 NameVals.push_back(P.AddressPointOffset);
4638 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4639 }
4640}
4641
4642// Adds the allocation contexts to the CallStacks map. We simply use the
4643// size at the time the context was added as the CallStackId. This works because
4644// when we look up the call stacks later on we process the function summaries
4645// and their allocation records in the same exact order.
4647 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4649 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4650 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4651 // currently uses unsigned. Make sure these stay in sync.
4652 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4653 for (auto &AI : FS->allocs()) {
4654 for (auto &MIB : AI.MIBs) {
4655 SmallVector<unsigned> StackIdIndices;
4656 StackIdIndices.reserve(MIB.StackIdIndices.size());
4657 for (auto Id : MIB.StackIdIndices)
4658 StackIdIndices.push_back(GetStackIndex(Id));
4659 // The CallStackId is the size at the time this context was inserted.
4660 CallStacks.insert({CallStacks.size(), StackIdIndices});
4661 }
4662 }
4663}
4664
4665// Build the radix tree from the accumulated CallStacks, write out the resulting
4666// linearized radix tree array, and return the map of call stack positions into
4667// this array for use when writing the allocation records. The returned map is
4668// indexed by a CallStackId which in this case is implicitly determined by the
4669// order of function summaries and their allocation infos being written.
4672 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4673 assert(!CallStacks.empty());
4674 DenseMap<unsigned, FrameStat> FrameHistogram =
4677 // We don't need a MemProfFrameIndexes map as we have already converted the
4678 // full stack id hash to a linear offset into the StackIds array.
4679 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4680 FrameHistogram);
4681 Stream.EmitRecord(bitc::FS_CONTEXT_RADIX_TREE_ARRAY, Builder.getRadixArray(),
4682 RadixAbbrev);
4683 return Builder.takeCallStackPos();
4684}
4685
4687 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4688 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4689 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4690 std::function<unsigned(unsigned)> GetStackIndex,
4691 bool WriteContextSizeInfoIndex,
4693 CallStackId &CallStackCount) {
4695
4696 for (auto &CI : FS->callsites()) {
4697 Record.clear();
4698 // Per module callsite clones should always have a single entry of
4699 // value 0.
4700 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4701 Record.push_back(GetValueID(CI.Callee));
4702 if (!PerModule) {
4703 Record.push_back(CI.StackIdIndices.size());
4704 Record.push_back(CI.Clones.size());
4705 }
4706 for (auto Id : CI.StackIdIndices)
4707 Record.push_back(GetStackIndex(Id));
4708 if (!PerModule)
4709 llvm::append_range(Record, CI.Clones);
4712 Record, CallsiteAbbrev);
4713 }
4714
4715 for (auto &AI : FS->allocs()) {
4716 Record.clear();
4717 // Per module alloc versions should always have a single entry of
4718 // value 0.
4719 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4720 Record.push_back(AI.MIBs.size());
4721 if (!PerModule)
4722 Record.push_back(AI.Versions.size());
4723 for (auto &MIB : AI.MIBs) {
4724 Record.push_back((uint8_t)MIB.AllocType);
4725 // The per-module summary always needs to include the alloc context, as we
4726 // use it during the thin link. For the combined index it is optional (see
4727 // comments where CombinedIndexMemProfContext is defined).
4728 if (PerModule || CombinedIndexMemProfContext) {
4729 // Record the index into the radix tree array for this context.
4730 assert(CallStackCount <= CallStackPos.size());
4731 Record.push_back(CallStackPos[CallStackCount++]);
4732 }
4733 }
4734 if (!PerModule)
4735 llvm::append_range(Record, AI.Versions);
4736 assert(AI.ContextSizeInfos.empty() ||
4737 AI.ContextSizeInfos.size() == AI.MIBs.size());
4738 // Optionally emit the context size information if it exists.
4739 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4740 // The abbreviation id for the context ids record should have been created
4741 // if we are emitting the per-module index, which is where we write this
4742 // info.
4743 assert(ContextIdAbbvId);
4744 SmallVector<uint32_t> ContextIds;
4745 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4746 // halves.
4747 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4748 for (auto &Infos : AI.ContextSizeInfos) {
4749 Record.push_back(Infos.size());
4750 for (auto [FullStackId, TotalSize] : Infos) {
4751 // The context ids are emitted separately as a fixed width array,
4752 // which is more efficient than a VBR given that these hashes are
4753 // typically close to 64-bits. The max fixed width entry is 32 bits so
4754 // it is split into 2.
4755 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4756 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4757 Record.push_back(TotalSize);
4758 }
4759 }
4760 // The context ids are expected by the reader to immediately precede the
4761 // associated alloc info record.
4762 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4763 ContextIdAbbvId);
4764 }
4765 Stream.EmitRecord(PerModule
4770 Record, AllocAbbrev);
4771 }
4772}
4773
4774// Helper to emit a single function summary record.
4775void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4776 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4777 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4778 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4779 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4780 CallStackId &CallStackCount) {
4781 NameVals.push_back(ValueID);
4782
4783 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4784
4786 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4787 return {VE.getValueID(VI.getValue())};
4788 });
4789
4790 auto SpecialRefCnts = FS->specialRefCounts();
4791 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4792 NameVals.push_back(FS->instCount());
4793 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4794 NameVals.push_back(FS->refs().size());
4795 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4796 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4797
4798 for (auto &RI : FS->refs())
4799 NameVals.push_back(getValueId(RI));
4800
4801 for (auto &ECI : FS->calls()) {
4802 NameVals.push_back(getValueId(ECI.first));
4803 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4804 }
4805
4806 // Emit the finished record.
4807 Stream.EmitRecord(bitc::FS_PERMODULE_PROFILE, NameVals, FSCallsProfileAbbrev);
4808 NameVals.clear();
4809
4811 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4812 /*PerModule*/ true,
4813 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4814 /*GetStackIndex*/ [&](unsigned I) { return I; },
4815 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4816}
4817
4818// Collect the global value references in the given variable's initializer,
4819// and emit them in a summary record.
4820void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4821 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4822 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4823 // Be a little lenient here, to accomodate older files without GUIDs
4824 // already computed and assigned as metadata.
4825 GlobalValue::GUID GUID = V.getGUIDOrFallback();
4826
4827 auto VI = Index->getValueInfo(GUID);
4828 if (!VI || VI.getSummaryList().empty()) {
4829 // Only declarations should not have a summary (a declaration might however
4830 // have a summary if the def was in module level asm).
4831 assert(V.isDeclaration());
4832 return;
4833 }
4834 auto *Summary = VI.getSummaryList()[0].get();
4835 NameVals.push_back(VE.getValueID(&V));
4836 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4837 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4838 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4839
4840 auto VTableFuncs = VS->vTableFuncs();
4841 if (!VTableFuncs.empty())
4842 NameVals.push_back(VS->refs().size());
4843
4844 unsigned SizeBeforeRefs = NameVals.size();
4845 for (auto &RI : VS->refs())
4846 NameVals.push_back(VE.getValueID(RI.getValue()));
4847 // Sort the refs for determinism output, the vector returned by FS->refs() has
4848 // been initialized from a DenseSet.
4849 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4850
4851 if (VTableFuncs.empty())
4853 FSModRefsAbbrev);
4854 else {
4855 // VTableFuncs pairs should already be sorted by offset.
4856 for (auto &P : VTableFuncs) {
4857 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4858 NameVals.push_back(P.VTableOffset);
4859 }
4860
4862 FSModVTableRefsAbbrev);
4863 }
4864 NameVals.clear();
4865}
4866
4867/// Emit the per-module summary section alongside the rest of
4868/// the module's bitcode.
4869void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4870 // By default we compile with ThinLTO if the module has a summary, but the
4871 // client can request full LTO with a module flag.
4872 bool IsThinLTO = true;
4873 if (auto *MD =
4874 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4875 IsThinLTO = MD->getZExtValue();
4878 4);
4879
4880 Stream.EmitRecord(
4882 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4883
4884 // Write the index flags.
4885 uint64_t Flags = 0;
4886 // Bits 1-3 are set only in the combined index, skip them.
4887 if (Index->enableSplitLTOUnit())
4888 Flags |= 0x8;
4889 if (Index->hasUnifiedLTO())
4890 Flags |= 0x200;
4891
4892 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4893
4894 if (Index->begin() == Index->end()) {
4895 Stream.ExitBlock();
4896 return;
4897 }
4898
4899 auto Abbv = std::make_shared<BitCodeAbbrev>();
4900 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4902 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4904 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4905 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4906
4907 for (const auto &GVI : valueIds()) {
4909 ArrayRef<uint32_t>{GVI.second,
4910 static_cast<uint32_t>(GVI.first >> 32),
4911 static_cast<uint32_t>(GVI.first)},
4912 ValueGuidAbbrev);
4913 }
4914
4915 if (!Index->stackIds().empty()) {
4916 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4917 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4918 // numids x stackid
4919 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4920 // The stack ids are hashes that are close to 64 bits in size, so emitting
4921 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4922 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4923 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4924 SmallVector<uint32_t> Vals;
4925 Vals.reserve(Index->stackIds().size() * 2);
4926 for (auto Id : Index->stackIds()) {
4927 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4928 Vals.push_back(static_cast<uint32_t>(Id));
4929 }
4930 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4931 }
4932
4933 unsigned ContextIdAbbvId = 0;
4935 // n x context id
4936 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4937 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4938 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4939 // The context ids are hashes that are close to 64 bits in size, so emitting
4940 // as a pair of 32-bit fixed-width values is more efficient than a VBR if we
4941 // are emitting them for all MIBs. Otherwise we use VBR to better compress 0
4942 // values that are expected to more frequently occur in an alloc's memprof
4943 // summary.
4945 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4946 else
4947 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4948 ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4949 }
4950
4951 // Abbrev for FS_PERMODULE_PROFILE.
4952 Abbv = std::make_shared<BitCodeAbbrev>();
4953 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
4954 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4955 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4961 // numrefs x valueid, n x (valueid, hotness+tailcall+indirectcall flags)
4962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4964 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4965
4966 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4967 Abbv = std::make_shared<BitCodeAbbrev>();
4968 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
4969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4973 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4974
4975 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4976 Abbv = std::make_shared<BitCodeAbbrev>();
4977 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
4978 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4981 // numrefs x valueid, n x (valueid , offset)
4982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4983 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4984 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4985
4986 // Abbrev for FS_ALIAS.
4987 Abbv = std::make_shared<BitCodeAbbrev>();
4988 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4992 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4993
4994 // Abbrev for FS_TYPE_ID_METADATA
4995 Abbv = std::make_shared<BitCodeAbbrev>();
4996 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4997 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4999 // n x (valueid , offset)
5000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5002 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5003
5004 Abbv = std::make_shared<BitCodeAbbrev>();
5005 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
5006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5007 // n x stackidindex
5008 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5009 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5010 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5011
5012 Abbv = std::make_shared<BitCodeAbbrev>();
5013 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
5014 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5015 // n x (alloc type, context radix tree index)
5016 // optional: nummib x (numcontext x total size)
5017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5018 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5019 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5020
5021 Abbv = std::make_shared<BitCodeAbbrev>();
5022 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5023 // n x entry
5024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5025 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5026 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5027
5028 // First walk through all the functions and collect the allocation contexts in
5029 // their associated summaries, for use in constructing a radix tree of
5030 // contexts. Note that we need to do this in the same order as the functions
5031 // are processed further below since the call stack positions in the resulting
5032 // radix tree array are identified based on this order.
5033 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5034 for (const Function &F : M) {
5035 // Summary emission does not support anonymous functions, they have to be
5036 // renamed using the anonymous function renaming pass.
5037 if (!F.hasName())
5038 report_fatal_error("Unexpected anonymous function when writing summary");
5039
5040 // Be a little lenient here, to accomodate older files without GUIDs
5041 // already computed and assigned as metadata.
5042 GlobalValue::GUID GUID = F.getGUIDOrFallback();
5043
5044 ValueInfo VI = Index->getValueInfo(GUID);
5045 if (!VI || VI.getSummaryList().empty()) {
5046 // Only declarations should not have a summary (a declaration might
5047 // however have a summary if the def was in module level asm).
5048 if (!F.isDeclaration())
5049 reportFatalUsageError("expected function definition " + F.getName() +
5050 " to have an associated value info.");
5051 continue;
5052 }
5053 auto *Summary = VI.getSummaryList()[0].get();
5054 FunctionSummary *FS = cast<FunctionSummary>(Summary);
5056 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
5057 }
5058 // Finalize the radix tree, write it out, and get the map of positions in the
5059 // linearized tree array.
5060 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5061 if (!CallStacks.empty()) {
5062 CallStackPos =
5063 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
5064 }
5065
5066 // Keep track of the current index into the CallStackPos map.
5067 CallStackId CallStackCount = 0;
5068
5069 SmallVector<uint64_t, 64> NameVals;
5070 // Iterate over the list of functions instead of the Index to
5071 // ensure the ordering is stable.
5072 for (const Function &F : M) {
5073 // Summary emission does not support anonymous functions, they have to
5074 // renamed using the anonymous function renaming pass.
5075 if (!F.hasName())
5076 report_fatal_error("Unexpected anonymous function when writing summary");
5077
5078 GlobalValue::GUID GUID = F.getGUIDOrFallback();
5079
5080 ValueInfo VI = Index->getValueInfo(GUID);
5081 if (!VI || VI.getSummaryList().empty()) {
5082 // Only declarations should not have a summary (a declaration might
5083 // however have a summary if the def was in module level asm).
5084 assert(F.isDeclaration());
5085 continue;
5086 }
5087 auto *Summary = VI.getSummaryList()[0].get();
5088 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
5089 FSCallsProfileAbbrev, CallsiteAbbrev,
5090 AllocAbbrev, ContextIdAbbvId, F,
5091 CallStackPos, CallStackCount);
5092 }
5093
5094 // Capture references from GlobalVariable initializers, which are outside
5095 // of a function scope.
5096 for (const GlobalVariable &G : M.globals())
5097 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
5098 FSModVTableRefsAbbrev);
5099
5100 for (const GlobalAlias &A : M.aliases()) {
5101 auto *Aliasee = A.getAliaseeObject();
5102 // Skip ifunc and nameless functions which don't have an entry in the
5103 // summary.
5104 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
5105 continue;
5106 auto AliasId = VE.getValueID(&A);
5107 auto AliaseeId = VE.getValueID(Aliasee);
5108 NameVals.push_back(AliasId);
5109 auto *Summary = Index->getGlobalValueSummary(A);
5110 AliasSummary *AS = cast<AliasSummary>(Summary);
5111 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
5112 NameVals.push_back(AliaseeId);
5113 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
5114 NameVals.clear();
5115 }
5116
5117 for (auto &S : Index->typeIdCompatibleVtableMap()) {
5118 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
5119 S.second, VE);
5120 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
5121 TypeIdCompatibleVtableAbbrev);
5122 NameVals.clear();
5123 }
5124
5125 if (Index->getBlockCount())
5127 ArrayRef<uint64_t>{Index->getBlockCount()});
5128
5129 Stream.ExitBlock();
5130}
5131
5132void ModuleBitcodeWriterBase::writeGUIDList() {
5134 for (const GlobalValue &GV : M.global_values()) {
5135 auto MaybeGUID = GV.getGUIDIfAssigned();
5136 if (!MaybeGUID || *MaybeGUID == 0)
5137 continue;
5138 const auto ValueID = VE.getValueID(&GV);
5139 if (ValueID >= GUIDs.size())
5140 GUIDs.resize(ValueID + 1);
5141 GUIDs[ValueID] = *MaybeGUID;
5142 }
5143
5144 auto Abbv = std::make_shared<BitCodeAbbrev>();
5145 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GUIDLIST));
5146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5148 unsigned GUIDListAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5149
5150 SmallVector<uint32_t> RecordVals;
5151 RecordVals.reserve(GUIDs.size() * 2);
5152 for (auto GUID : GUIDs) {
5153 RecordVals.push_back(static_cast<uint32_t>(GUID >> 32));
5154 RecordVals.push_back(static_cast<uint32_t>(GUID));
5155 }
5156
5157 Stream.EmitRecord(bitc::MODULE_CODE_GUIDLIST, RecordVals, GUIDListAbbrev);
5158}
5159
5160/// Emit the combined summary section into the combined index file.
5161void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5163 Stream.EmitRecord(
5165 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
5166
5167 // Write the index flags.
5168 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
5169
5170 auto Abbv = std::make_shared<BitCodeAbbrev>();
5171 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
5172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
5173 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
5174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5176 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5177
5178 for (const auto &GVI : valueIds()) {
5180 ArrayRef<uint32_t>{GVI.second,
5181 static_cast<uint32_t>(GVI.first >> 32),
5182 static_cast<uint32_t>(GVI.first)},
5183 ValueGuidAbbrev);
5184 }
5185
5186 // Write the stack ids used by this index, which will be a subset of those in
5187 // the full index in the case of distributed indexes.
5188 if (!StackIds.empty()) {
5189 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5190 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
5191 // numids x stackid
5192 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5193 // The stack ids are hashes that are close to 64 bits in size, so emitting
5194 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
5195 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5196 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
5197 SmallVector<uint32_t> Vals;
5198 Vals.reserve(StackIds.size() * 2);
5199 for (auto Id : StackIds) {
5200 Vals.push_back(static_cast<uint32_t>(Id >> 32));
5201 Vals.push_back(static_cast<uint32_t>(Id));
5202 }
5203 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
5204 }
5205
5206 // Abbrev for FS_COMBINED_PROFILE.
5207 Abbv = std::make_shared<BitCodeAbbrev>();
5208 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
5209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
5213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
5214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
5215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
5216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
5217 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
5218 // numrefs x valueid, n x (valueid, hotness+tailcall+indirectcall flags)
5219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5221 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5222
5223 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
5224 Abbv = std::make_shared<BitCodeAbbrev>();
5225 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
5226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
5230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5231 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5232
5233 // Abbrev for FS_COMBINED_ALIAS.
5234 Abbv = std::make_shared<BitCodeAbbrev>();
5235 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
5236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5238 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5239 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5240 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5241
5242 Abbv = std::make_shared<BitCodeAbbrev>();
5243 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
5244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
5246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5247 // numstackindices x stackidindex, numver x version
5248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5250 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5251
5252 Abbv = std::make_shared<BitCodeAbbrev>();
5253 Abbv->Add(BitCodeAbbrevOp(CombinedIndexMemProfContext
5256 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5258 // nummib x (alloc type, context radix tree index),
5259 // numver x version
5260 // optional: nummib x total size
5261 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5263 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5264
5265 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
5266 if (DecSummaries == nullptr)
5267 return false;
5268 return DecSummaries->count(GVS);
5269 };
5270
5271 // The aliases are emitted as a post-pass, and will point to the value
5272 // id of the aliasee. Save them in a vector for post-processing.
5274
5275 // Save the value id for each summary for alias emission.
5276 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5277
5278 SmallVector<uint64_t, 64> NameVals;
5279
5280 // Set that will be populated during call to writeFunctionTypeMetadataRecords
5281 // with the type ids referenced by this index file.
5282 std::set<GlobalValue::GUID> ReferencedTypeIds;
5283
5284 // For local linkage, we also emit the original name separately
5285 // immediately after the record.
5286 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5287 // We don't need to emit the original name if we are writing the index for
5288 // distributed backends (in which case ModuleToSummariesForIndex is
5289 // non-null). The original name is only needed during the thin link, since
5290 // for SamplePGO the indirect call targets for local functions have
5291 // have the original name annotated in profile.
5292 // Continue to emit it when writing out the entire combined index, which is
5293 // used in testing the thin link via llvm-lto.
5294 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
5295 return;
5296 NameVals.push_back(S.getOriginalName());
5298 NameVals.clear();
5299 };
5300
5301 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5303 Abbv = std::make_shared<BitCodeAbbrev>();
5304 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5305 // n x entry
5306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5307 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5308 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5309
5310 // First walk through all the functions and collect the allocation contexts
5311 // in their associated summaries, for use in constructing a radix tree of
5312 // contexts. Note that we need to do this in the same order as the functions
5313 // are processed further below since the call stack positions in the
5314 // resulting radix tree array are identified based on this order.
5315 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5316 forEachSummary([&](GVInfo I, bool IsAliasee) {
5317 // Don't collect this when invoked for an aliasee, as it is not needed for
5318 // the alias summary. If the aliasee is to be imported, we will invoke
5319 // this separately with IsAliasee=false.
5320 if (IsAliasee)
5321 return;
5322 GlobalValueSummary *S = I.second;
5323 assert(S);
5324 auto *FS = dyn_cast<FunctionSummary>(S);
5325 if (!FS)
5326 return;
5328 FS,
5329 /*GetStackIndex*/
5330 [&](unsigned I) {
5331 // Get the corresponding index into the list of StackIds actually
5332 // being written for this combined index (which may be a subset in
5333 // the case of distributed indexes).
5334 assert(StackIdIndicesToIndex.contains(I));
5335 return StackIdIndicesToIndex[I];
5336 },
5337 CallStacks);
5338 });
5339 // Finalize the radix tree, write it out, and get the map of positions in
5340 // the linearized tree array.
5341 if (!CallStacks.empty()) {
5342 CallStackPos = writeMemoryProfileRadixTree(std::move(CallStacks), Stream,
5343 RadixAbbrev);
5344 }
5345 }
5346
5347 // Keep track of the current index into the CallStackPos map. Not used if
5348 // CombinedIndexMemProfContext is false.
5349 CallStackId CallStackCount = 0;
5350
5351 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5352 forEachSummary([&](GVInfo I, bool IsAliasee) {
5353 GlobalValueSummary *S = I.second;
5354 assert(S);
5355 DefOrUseGUIDs.insert(I.first);
5356 for (const ValueInfo &VI : S->refs())
5357 DefOrUseGUIDs.insert(VI.getGUID());
5358
5359 auto ValueId = getValueId(I.first);
5360 assert(ValueId);
5361 SummaryToValueIdMap[S] = *ValueId;
5362
5363 // If this is invoked for an aliasee, we want to record the above
5364 // mapping, but then not emit a summary entry (if the aliasee is
5365 // to be imported, we will invoke this separately with IsAliasee=false).
5366 if (IsAliasee)
5367 return;
5368
5369 if (auto *AS = dyn_cast<AliasSummary>(S)) {
5370 // Will process aliases as a post-pass because the reader wants all
5371 // global to be loaded first.
5372 Aliases.push_back(AS);
5373 return;
5374 }
5375
5376 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
5377 NameVals.push_back(*ValueId);
5378 assert(ModuleIdMap.count(VS->modulePath()));
5379 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
5380 NameVals.push_back(
5381 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
5382 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
5383 for (auto &RI : VS->refs()) {
5384 auto RefValueId = getValueId(RI.getGUID());
5385 if (!RefValueId)
5386 continue;
5387 NameVals.push_back(*RefValueId);
5388 }
5389
5390 // Emit the finished record.
5392 FSModRefsAbbrev);
5393 NameVals.clear();
5394 MaybeEmitOriginalName(*S);
5395 return;
5396 }
5397
5398 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
5399 if (!VI)
5400 return std::nullopt;
5401 return getValueId(VI.getGUID());
5402 };
5403
5404 auto *FS = cast<FunctionSummary>(S);
5405 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
5406 getReferencedTypeIds(FS, ReferencedTypeIds);
5407
5408 NameVals.push_back(*ValueId);
5409 assert(ModuleIdMap.count(FS->modulePath()));
5410 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
5411 NameVals.push_back(
5412 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
5413 NameVals.push_back(FS->instCount());
5414 NameVals.push_back(getEncodedFFlags(FS->fflags()));
5415 // TODO: Stop writing entry count and bump bitcode version.
5416 NameVals.push_back(0 /* EntryCount */);
5417
5418 // Fill in below
5419 NameVals.push_back(0); // numrefs
5420 NameVals.push_back(0); // rorefcnt
5421 NameVals.push_back(0); // worefcnt
5422
5423 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5424 for (auto &RI : FS->refs()) {
5425 auto RefValueId = getValueId(RI.getGUID());
5426 if (!RefValueId)
5427 continue;
5428 NameVals.push_back(*RefValueId);
5429 if (RI.isReadOnly())
5430 RORefCnt++;
5431 else if (RI.isWriteOnly())
5432 WORefCnt++;
5433 Count++;
5434 }
5435 NameVals[6] = Count;
5436 NameVals[7] = RORefCnt;
5437 NameVals[8] = WORefCnt;
5438
5439 for (auto &EI : FS->calls()) {
5440 // If this GUID doesn't have a value id, it doesn't have a function
5441 // summary and we don't need to record any calls to it.
5442 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5443 if (!CallValueId)
5444 continue;
5445 NameVals.push_back(*CallValueId);
5446 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
5447 }
5448
5449 // Emit the finished record.
5450 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5451 FSCallsProfileAbbrev);
5452 NameVals.clear();
5453
5455 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
5456 /*PerModule*/ false,
5457 /*GetValueId*/
5458 [&](const ValueInfo &VI) -> unsigned {
5459 std::optional<unsigned> ValueID = GetValueId(VI);
5460 // This can happen in shared index files for distributed ThinLTO if
5461 // the callee function summary is not included. Record 0 which we
5462 // will have to deal with conservatively when doing any kind of
5463 // validation in the ThinLTO backends.
5464 if (!ValueID)
5465 return 0;
5466 return *ValueID;
5467 },
5468 /*GetStackIndex*/
5469 [&](unsigned I) {
5470 // Get the corresponding index into the list of StackIds actually
5471 // being written for this combined index (which may be a subset in
5472 // the case of distributed indexes).
5473 assert(StackIdIndicesToIndex.contains(I));
5474 return StackIdIndicesToIndex[I];
5475 },
5476 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
5477
5478 MaybeEmitOriginalName(*S);
5479 });
5480
5481 for (auto *AS : Aliases) {
5482 auto AliasValueId = SummaryToValueIdMap[AS];
5483 assert(AliasValueId);
5484 NameVals.push_back(AliasValueId);
5485 assert(ModuleIdMap.count(AS->modulePath()));
5486 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5487 NameVals.push_back(
5488 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5489 // Set value id to 0 when an alias is imported but the aliasee summary is
5490 // not contained in the index.
5491 auto AliaseeValueId =
5492 AS->hasAliasee() ? SummaryToValueIdMap[&AS->getAliasee()] : 0;
5493 NameVals.push_back(AliaseeValueId);
5494
5495 // Emit the finished record.
5496 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5497 NameVals.clear();
5498 MaybeEmitOriginalName(*AS);
5499
5500 if (AS->hasAliasee())
5501 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5502 getReferencedTypeIds(FS, ReferencedTypeIds);
5503 }
5504
5506 auto EmitCfiFunctions = [&](const CfiFunctionIndex &CfiIndex,
5508 if (CfiIndex.empty())
5509 return;
5510 for (GlobalValue::GUID GUID : DefOrUseGUIDs) {
5511 auto Names = CfiIndex.getNamesForGUID(GUID);
5512 for (StringRef Name : Names)
5513 Functions.push_back({Name, GUID});
5514 }
5515 if (Functions.empty())
5516 return;
5517 llvm::sort(Functions);
5518 for (const auto &Record : Functions) {
5519 NameVals.push_back(Record.second);
5520 NameVals.push_back(StrtabBuilder.add(Record.first));
5521 NameVals.push_back(Record.first.size());
5522 }
5523 Stream.EmitRecord(Code, NameVals);
5524 NameVals.clear();
5525 Functions.clear();
5526 };
5527
5528 EmitCfiFunctions(Index.cfiFunctionDefs(), bitc::FS_CFI_FUNCTION_DEFS);
5529 EmitCfiFunctions(Index.cfiFunctionDecls(), bitc::FS_CFI_FUNCTION_DECLS);
5530
5531 // Walk the GUIDs that were referenced, and write the
5532 // corresponding type id records.
5533 for (auto &T : ReferencedTypeIds) {
5534 auto TidIter = Index.typeIds().equal_range(T);
5535 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5536 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5537 TypeIdPair.second);
5538 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5539 NameVals.clear();
5540 }
5541 }
5542
5543 if (Index.getBlockCount())
5545 ArrayRef<uint64_t>{Index.getBlockCount()});
5546
5547 Stream.ExitBlock();
5548}
5549
5550/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5551/// current llvm version, and a record for the epoch number.
5554
5555 // Write the "user readable" string identifying the bitcode producer
5556 auto Abbv = std::make_shared<BitCodeAbbrev>();
5560 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5562 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5563
5564 // Write the epoch version
5565 Abbv = std::make_shared<BitCodeAbbrev>();
5568 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5569 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5570 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5571 Stream.ExitBlock();
5572}
5573
5574void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5575 // Emit the module's hash.
5576 // MODULE_CODE_HASH: [5*i32]
5577 if (GenerateHash) {
5578 uint32_t Vals[5];
5579 Hasher.update(ArrayRef<uint8_t>(
5580 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5581 std::array<uint8_t, 20> Hash = Hasher.result();
5582 for (int Pos = 0; Pos < 20; Pos += 4) {
5583 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5584 }
5585
5586 // Emit the finished record.
5587 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5588
5589 if (ModHash)
5590 // Save the written hash value.
5591 llvm::copy(Vals, std::begin(*ModHash));
5592 }
5593}
5594
5595void ModuleBitcodeWriter::write() {
5597
5599 // We will want to write the module hash at this point. Block any flushing so
5600 // we can have access to the whole underlying data later.
5601 Stream.markAndBlockFlushing();
5602
5603 writeModuleVersion();
5604
5605 // Emit blockinfo, which defines the standard abbreviations etc.
5606 writeBlockInfo();
5607
5608 // Emit information describing all of the types in the module.
5609 writeTypeTable();
5610
5611 // Emit information about attribute groups.
5612 writeAttributeGroupTable();
5613
5614 // Emit information about parameter attributes.
5615 writeAttributeTable();
5616
5617 writeComdats();
5618
5619 // Emit top-level description of module, including target triple, inline asm,
5620 // descriptors for global variables, and function prototype info.
5621 writeModuleInfo();
5622
5623 // Emit constants.
5624 writeModuleConstants();
5625
5626 // Emit metadata kind names.
5627 writeModuleMetadataKinds();
5628
5629 // Emit metadata.
5630 writeModuleMetadata();
5631
5632 // Emit module-level use-lists.
5634 writeUseListBlock(nullptr);
5635
5636 writeOperandBundleTags();
5637 writeSyncScopeNames();
5638
5639 // Emit function bodies.
5640 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5641 for (const Function &F : M)
5642 if (!F.isDeclaration())
5643 writeFunction(F, FunctionToBitcodeIndex);
5644
5645 // Need to write after the above call to WriteFunction which populates
5646 // the summary information in the index.
5647 if (Index)
5648 writePerModuleGlobalValueSummary();
5649
5650 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5651
5652 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5653
5654 Stream.ExitBlock();
5655}
5656
5658 uint32_t &Position) {
5659 support::endian::write32le(&Buffer[Position], Value);
5660 Position += 4;
5661}
5662
5663/// If generating a bc file on darwin, we have to emit a
5664/// header and trailer to make it compatible with the system archiver. To do
5665/// this we emit the following header, and then emit a trailer that pads the
5666/// file out to be a multiple of 16 bytes.
5667///
5668/// struct bc_header {
5669/// uint32_t Magic; // 0x0B17C0DE
5670/// uint32_t Version; // Version, currently always 0.
5671/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5672/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5673/// uint32_t CPUType; // CPU specifier.
5674/// ... potentially more later ...
5675/// };
5677 const Triple &TT) {
5678 unsigned CPUType = ~0U;
5679
5680 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5681 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5682 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5683 // specific constants here because they are implicitly part of the Darwin ABI.
5684 enum {
5685 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5686 DARWIN_CPU_TYPE_X86 = 7,
5687 DARWIN_CPU_TYPE_ARM = 12,
5688 DARWIN_CPU_TYPE_POWERPC = 18
5689 };
5690
5691 Triple::ArchType Arch = TT.getArch();
5692 if (Arch == Triple::x86_64)
5693 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5694 else if (Arch == Triple::x86)
5695 CPUType = DARWIN_CPU_TYPE_X86;
5696 else if (Arch == Triple::ppc)
5697 CPUType = DARWIN_CPU_TYPE_POWERPC;
5698 else if (Arch == Triple::ppc64)
5699 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5700 else if (Arch == Triple::arm || Arch == Triple::thumb)
5701 CPUType = DARWIN_CPU_TYPE_ARM;
5702
5703 // Traditional Bitcode starts after header.
5704 assert(Buffer.size() >= BWH_HeaderSize &&
5705 "Expected header size to be reserved");
5706 unsigned BCOffset = BWH_HeaderSize;
5707 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5708
5709 // Write the magic and version.
5710 unsigned Position = 0;
5711 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5712 writeInt32ToBuffer(0, Buffer, Position); // Version.
5713 writeInt32ToBuffer(BCOffset, Buffer, Position);
5714 writeInt32ToBuffer(BCSize, Buffer, Position);
5715 writeInt32ToBuffer(CPUType, Buffer, Position);
5716
5717 // If the file is not a multiple of 16 bytes, insert dummy padding.
5718 while (Buffer.size() & 15)
5719 Buffer.push_back(0);
5720}
5721
5722/// Helper to write the header common to all bitcode files.
5724 // Emit the file header.
5725 Stream.Emit((unsigned)'B', 8);
5726 Stream.Emit((unsigned)'C', 8);
5727 Stream.Emit(0x0, 4);
5728 Stream.Emit(0xC, 4);
5729 Stream.Emit(0xE, 4);
5730 Stream.Emit(0xD, 4);
5731}
5732
5734 : Stream(new BitstreamWriter(Buffer)) {
5735 writeBitcodeHeader(*Stream);
5736}
5737
5742
5744
5745void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5746 Stream->EnterSubblock(Block, 3);
5747
5748 auto Abbv = std::make_shared<BitCodeAbbrev>();
5749 Abbv->Add(BitCodeAbbrevOp(Record));
5751 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5752
5753 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5754
5755 Stream->ExitBlock();
5756}
5757
5759 assert(!WroteStrtab && !WroteSymtab);
5760
5761 // If any module has module-level inline asm, we will require a registered asm
5762 // parser for the target so that we can create an accurate symbol table for
5763 // the module.
5764 for (Module *M : Mods) {
5765 if (M->getModuleInlineAsm().empty())
5766 continue;
5767
5768 std::string Err;
5769 const Triple TT(M->getTargetTriple());
5770 const Target *T = TargetRegistry::lookupTarget(TT, Err);
5771 if (!T || !T->hasMCAsmParser())
5772 return;
5773 }
5774
5775 WroteSymtab = true;
5776 SmallVector<char, 0> Symtab;
5777 // The irsymtab::build function may be unable to create a symbol table if the
5778 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5779 // table is not required for correctness, but we still want to be able to
5780 // write malformed modules to bitcode files, so swallow the error.
5781 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5782 consumeError(std::move(E));
5783 return;
5784 }
5785
5787 {Symtab.data(), Symtab.size()});
5788}
5789
5791 assert(!WroteStrtab);
5792
5793 std::vector<char> Strtab;
5794 StrtabBuilder.finalizeInOrder();
5795 Strtab.resize(StrtabBuilder.getSize());
5796 StrtabBuilder.write((uint8_t *)Strtab.data());
5797
5799 {Strtab.data(), Strtab.size()});
5800
5801 WroteStrtab = true;
5802}
5803
5805 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5806 WroteStrtab = true;
5807}
5808
5810 bool ShouldPreserveUseListOrder,
5811 const ModuleSummaryIndex *Index,
5812 bool GenerateHash, ModuleHash *ModHash) {
5813 assert(!WroteStrtab);
5814
5815 // The Mods vector is used by irsymtab::build, which requires non-const
5816 // Modules in case it needs to materialize metadata. But the bitcode writer
5817 // requires that the module is materialized, so we can cast to non-const here,
5818 // after checking that it is in fact materialized.
5819 assert(M.isMaterialized());
5820 Mods.push_back(const_cast<Module *>(&M));
5821
5822 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5823 ShouldPreserveUseListOrder, Index,
5824 GenerateHash, ModHash);
5825 ModuleWriter.write();
5826}
5827
5829 const ModuleSummaryIndex *Index,
5830 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5831 const GVSummaryPtrSet *DecSummaries) {
5832 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5833 ModuleToSummariesForIndex);
5834 IndexWriter.write();
5835}
5836
5837/// Write the specified module to the specified output stream.
5839 bool ShouldPreserveUseListOrder,
5840 const ModuleSummaryIndex *Index,
5841 bool GenerateHash, ModuleHash *ModHash) {
5842 auto Write = [&](BitcodeWriter &Writer) {
5843 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5844 ModHash);
5845 Writer.writeSymtab();
5846 Writer.writeStrtab();
5847 };
5848 Triple TT(M.getTargetTriple());
5849 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5850 // If this is darwin or another generic macho target, reserve space for the
5851 // header. Note that the header is computed *after* the output is known, so
5852 // we currently explicitly use a buffer, write to it, and then subsequently
5853 // flush to Out.
5854 SmallVector<char, 0> Buffer;
5855 Buffer.reserve(256 * 1024);
5856 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5857 BitcodeWriter Writer(Buffer);
5858 Write(Writer);
5859 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5860 Out.write(Buffer.data(), Buffer.size());
5861 } else {
5862 BitcodeWriter Writer(Out);
5863 Write(Writer);
5864 }
5865}
5866
5867void IndexBitcodeWriter::write() {
5869
5870 writeModuleVersion();
5871
5872 // Write the module paths in the combined index.
5873 writeModStrings();
5874
5875 // Write the summary combined index records.
5876 writeCombinedGlobalValueSummary();
5877
5878 Stream.ExitBlock();
5879}
5880
5881// Write the specified module summary index to the given raw output stream,
5882// where it will be written in a new bitcode block. This is used when
5883// writing the combined index file for ThinLTO. When writing a subset of the
5884// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5886 const ModuleSummaryIndex &Index, raw_ostream &Out,
5887 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5888 const GVSummaryPtrSet *DecSummaries) {
5889 SmallVector<char, 0> Buffer;
5890 Buffer.reserve(256 * 1024);
5891
5892 BitcodeWriter Writer(Buffer);
5893 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5894 Writer.writeStrtab();
5895
5896 Out.write((char *)&Buffer.front(), Buffer.size());
5897}
5898
5899namespace {
5900
5901/// Class to manage the bitcode writing for a thin link bitcode file.
5902class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5903 /// ModHash is for use in ThinLTO incremental build, generated while writing
5904 /// the module bitcode file.
5905 const ModuleHash *ModHash;
5906
5907public:
5908 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5909 BitstreamWriter &Stream,
5910 const ModuleSummaryIndex &Index,
5911 const ModuleHash &ModHash)
5912 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5913 /*ShouldPreserveUseListOrder=*/false, &Index),
5914 ModHash(&ModHash) {}
5915
5916 void write();
5917
5918private:
5919 void writeSimplifiedModuleInfo();
5920};
5921
5922} // end anonymous namespace
5923
5924// This function writes a simpilified module info for thin link bitcode file.
5925// It only contains the source file name along with the name(the offset and
5926// size in strtab) and linkage for global values. For the global value info
5927// entry, in order to keep linkage at offset 5, there are three zeros used
5928// as padding.
5929void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5931 // Emit the module's source file name.
5932 {
5933 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5935 if (Bits == SE_Char6)
5936 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5937 else if (Bits == SE_Fixed7)
5938 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5939
5940 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5941 auto Abbv = std::make_shared<BitCodeAbbrev>();
5944 Abbv->Add(AbbrevOpToUse);
5945 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5946
5947 for (const auto P : M.getSourceFileName())
5948 Vals.push_back((unsigned char)P);
5949
5950 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5951 Vals.clear();
5952 }
5953
5954 writeGUIDList();
5955
5956 // Emit the global variable information.
5957 for (const GlobalVariable &GV : M.globals()) {
5958 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5959 Vals.push_back(StrtabBuilder.add(GV.getName()));
5960 Vals.push_back(GV.getName().size());
5961 Vals.push_back(0);
5962 Vals.push_back(0);
5963 Vals.push_back(0);
5964 Vals.push_back(getEncodedLinkage(GV));
5965
5967 Vals.clear();
5968 }
5969
5970 // Emit the function proto information.
5971 for (const Function &F : M) {
5972 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5973 Vals.push_back(StrtabBuilder.add(F.getName()));
5974 Vals.push_back(F.getName().size());
5975 Vals.push_back(0);
5976 Vals.push_back(0);
5977 Vals.push_back(0);
5979
5981 Vals.clear();
5982 }
5983
5984 // Emit the alias information.
5985 for (const GlobalAlias &A : M.aliases()) {
5986 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5987 Vals.push_back(StrtabBuilder.add(A.getName()));
5988 Vals.push_back(A.getName().size());
5989 Vals.push_back(0);
5990 Vals.push_back(0);
5991 Vals.push_back(0);
5993
5994 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5995 Vals.clear();
5996 }
5997
5998 // Emit the ifunc information.
5999 for (const GlobalIFunc &I : M.ifuncs()) {
6000 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
6001 Vals.push_back(StrtabBuilder.add(I.getName()));
6002 Vals.push_back(I.getName().size());
6003 Vals.push_back(0);
6004 Vals.push_back(0);
6005 Vals.push_back(0);
6007
6008 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
6009 Vals.clear();
6010 }
6011}
6012
6013void ThinLinkBitcodeWriter::write() {
6015
6016 writeModuleVersion();
6017
6018 writeSimplifiedModuleInfo();
6019
6020 writePerModuleGlobalValueSummary();
6021
6022 // Write module hash.
6024
6025 Stream.ExitBlock();
6026}
6027
6029 const ModuleSummaryIndex &Index,
6030 const ModuleHash &ModHash) {
6031 assert(!WroteStrtab);
6032
6033 // The Mods vector is used by irsymtab::build, which requires non-const
6034 // Modules in case it needs to materialize metadata. But the bitcode writer
6035 // requires that the module is materialized, so we can cast to non-const here,
6036 // after checking that it is in fact materialized.
6037 assert(M.isMaterialized());
6038 Mods.push_back(const_cast<Module *>(&M));
6039
6040 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6041 ModHash);
6042 ThinLinkWriter.write();
6043}
6044
6045// Write the specified thin link bitcode file to the given raw output stream,
6046// where it will be written in a new bitcode block. This is used when
6047// writing the per-module index file for ThinLTO.
6049 const ModuleSummaryIndex &Index,
6050 const ModuleHash &ModHash) {
6051 SmallVector<char, 0> Buffer;
6052 Buffer.reserve(256 * 1024);
6053
6054 BitcodeWriter Writer(Buffer);
6055 Writer.writeThinLinkBitcode(M, Index, ModHash);
6056 Writer.writeSymtab();
6057 Writer.writeStrtab();
6058
6059 Out.write((char *)&Buffer.front(), Buffer.size());
6060}
6061
6062static const char *getSectionNameForBitcode(const Triple &T) {
6063 switch (T.getObjectFormat()) {
6064 case Triple::MachO:
6065 return "__LLVM,__bitcode";
6066 case Triple::COFF:
6067 case Triple::ELF:
6068 case Triple::Wasm:
6070 return ".llvmbc";
6071 case Triple::GOFF:
6072 llvm_unreachable("GOFF is not yet implemented");
6073 break;
6074 case Triple::SPIRV:
6075 if (T.getVendor() == Triple::AMD)
6076 return ".llvmbc";
6077 llvm_unreachable("SPIRV is not yet implemented");
6078 break;
6079 case Triple::XCOFF:
6080 llvm_unreachable("XCOFF is not yet implemented");
6081 break;
6083 llvm_unreachable("DXContainer is not yet implemented");
6084 break;
6085 }
6086 llvm_unreachable("Unimplemented ObjectFormatType");
6087}
6088
6089static const char *getSectionNameForCommandline(const Triple &T) {
6090 switch (T.getObjectFormat()) {
6091 case Triple::MachO:
6092 return "__LLVM,__cmdline";
6093 case Triple::COFF:
6094 case Triple::ELF:
6095 case Triple::Wasm:
6097 return ".llvmcmd";
6098 case Triple::GOFF:
6099 llvm_unreachable("GOFF is not yet implemented");
6100 break;
6101 case Triple::SPIRV:
6102 if (T.getVendor() == Triple::AMD)
6103 return ".llvmcmd";
6104 llvm_unreachable("SPIRV is not yet implemented");
6105 break;
6106 case Triple::XCOFF:
6107 llvm_unreachable("XCOFF is not yet implemented");
6108 break;
6110 llvm_unreachable("DXC is not yet implemented");
6111 break;
6112 }
6113 llvm_unreachable("Unimplemented ObjectFormatType");
6114}
6115
6117 bool EmbedBitcode, bool EmbedCmdline,
6118 const std::vector<uint8_t> &CmdArgs) {
6119 // Save llvm.compiler.used and remove it.
6122 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
6123 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6124 : PointerType::getUnqual(M.getContext());
6125 for (auto *GV : UsedGlobals) {
6126 if (GV->getName() != "llvm.embedded.module" &&
6127 GV->getName() != "llvm.cmdline")
6128 UsedArray.push_back(
6130 }
6131 if (Used)
6132 Used->eraseFromParent();
6133
6134 // Embed the bitcode for the llvm module.
6135 std::string Data;
6136 ArrayRef<uint8_t> ModuleData;
6137 Triple T(M.getTargetTriple());
6138
6139 if (EmbedBitcode) {
6140 if (Buf.getBufferSize() == 0 ||
6141 !isBitcode((const unsigned char *)Buf.getBufferStart(),
6142 (const unsigned char *)Buf.getBufferEnd())) {
6143 // If the input is LLVM Assembly, bitcode is produced by serializing
6144 // the module. Use-lists order need to be preserved in this case.
6146 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
6147 ModuleData =
6148 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
6149 } else
6150 // If the input is LLVM bitcode, write the input byte stream directly.
6151 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
6152 Buf.getBufferSize());
6153 }
6154 llvm::Constant *ModuleConstant =
6155 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
6157 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
6158 ModuleConstant);
6160 // Set alignment to 1 to prevent padding between two contributions from input
6161 // sections after linking.
6162 GV->setAlignment(Align(1));
6163 UsedArray.push_back(
6165 if (llvm::GlobalVariable *Old =
6166 M.getGlobalVariable("llvm.embedded.module", true)) {
6167 assert(Old->hasZeroLiveUses() &&
6168 "llvm.embedded.module can only be used once in llvm.compiler.used");
6169 GV->takeName(Old);
6170 Old->eraseFromParent();
6171 } else {
6172 GV->setName("llvm.embedded.module");
6173 }
6174
6175 // Skip if only bitcode needs to be embedded.
6176 if (EmbedCmdline) {
6177 // Embed command-line options.
6178 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
6179 CmdArgs.size());
6180 llvm::Constant *CmdConstant =
6181 llvm::ConstantDataArray::get(M.getContext(), CmdData);
6182 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
6184 CmdConstant);
6186 GV->setAlignment(Align(1));
6187 UsedArray.push_back(
6189 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
6190 assert(Old->hasZeroLiveUses() &&
6191 "llvm.cmdline can only be used once in llvm.compiler.used");
6192 GV->takeName(Old);
6193 Old->eraseFromParent();
6194 } else {
6195 GV->setName("llvm.cmdline");
6196 }
6197 }
6198
6199 if (UsedArray.empty())
6200 return;
6201
6202 // Recreate llvm.compiler.used.
6203 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
6204 auto *NewUsed = new GlobalVariable(
6206 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
6207 NewUsed->setSection("llvm.metadata");
6208}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDIProperty(raw_ostream &Out, const DIProperty *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
StringEncoding
@ SE_Char6
@ SE_Fixed7
@ SE_Fixed8
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static cl::opt< bool > PreserveBitcodeUseListOrder("preserve-bc-uselistorder", cl::Hidden, cl::init(true), cl::desc("Preserve use-list order when writing LLVM bitcode."))
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< uint32_t > FlushThreshold("bitcode-flush-threshold", cl::Hidden, cl::init(512), cl::desc("The threshold (unit M) for flushing LLVM bitcode."))
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
MetadataAbbrev
@ LastPlusOne
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
#define T
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
nvptx lower args
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
Definition APInt.h:1538
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:571
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
bool hasAttributes() const
Return true if attributes exists in this set.
Definition Attributes.h:484
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
Definition Attributes.h:132
@ None
No attributes have been set.
Definition Attributes.h:127
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
Definition Attributes.h:131
@ EndAttrKinds
Sentinel value useful for loops.
Definition Attributes.h:130
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
Definition BitCodes.h:34
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
Definition BitCodes.h:88
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:44
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
idx_iterator idx_end() const
idx_iterator idx_begin() const
Function summary information to aid decisions and implementation of importing.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCast() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
bool empty() const
Definition MapVector.h:79
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition SHA1.cpp:208
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
Definition SHA1.cpp:288
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
StringRef getKey() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
@ UnknownObjectFormat
Definition Triple.h:422
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition Type.h:161
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition Type.h:164
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
Value * getValue() const
Definition Metadata.h:510
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ Entry
Definition COFF.h:862
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
@ TYPE_CODE_TARGET_TYPE
@ TYPE_CODE_STRUCT_ANON
@ TYPE_CODE_STRUCT_NAME
@ TYPE_CODE_OPAQUE_POINTER
@ TYPE_CODE_STRUCT_NAMED
@ METADATA_COMMON_BLOCK
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_INDEX_OFFSET
@ METADATA_LEXICAL_BLOCK
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_OBJC_PROPERTY
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPILE_UNIT
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_LAYERLOCLIST
@ METADATA_DERIVED_TYPE
@ METADATA_SUBRANGE_TYPE
@ METADATA_TEMPLATE_TYPE
@ METADATA_GLOBAL_VAR_EXPR
@ METADATA_DISTINCT_NODE
@ METADATA_GENERIC_DEBUG
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_CFI_FUNCTION_DECLS
@ FS_COMBINED_CALLSITE_INFO
@ FS_COMBINED_ALLOC_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ BITCODE_CURRENT_EPOCH
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_BLOCKADDRESS
@ CST_CODE_NO_CFI_VALUE
@ CST_CODE_CE_SHUFVEC_EX
@ CST_CODE_CE_EXTRACTELT
@ CST_CODE_CE_SHUFFLEVEC
@ CST_CODE_WIDE_INTEGER
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_INSERTELT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_SWIFT_ERROR
@ ATTR_KIND_NO_CALLBACK
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_INLINE_HINT
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_MUSTPROGRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_INITIALIZES
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_SKIP_PROFILE
@ ATTR_KIND_ELEMENTTYPE
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NO_DUPLICATE
@ ATTR_KIND_ALLOC_ALIGN
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_NO_RED_ZONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_VSCALE_RANGE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_SPECULATABLE
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ ATTR_KIND_PREALLOCATED
@ ATTR_KIND_SWIFT_ASYNC
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ METADATA_KIND_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ METADATA_ATTACHMENT_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ MODULE_STRTAB_BLOCK_ID
@ VALUE_SYMTAB_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_VERSION
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_DATALAYOUT
@ MODULE_CODE_GLOBALVAR
@ MODULE_CODE_VSTOFFSET
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_RESUME
@ FUNC_CODE_INST_CALLBR
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_VSELECT
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_INST_INVOKE
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_SWITCH
@ FUNC_CODE_INST_ALLOCA
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_FREEZE
@ FUNC_CODE_INST_CMPXCHG
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
Definition IRSymtab.cpp:348
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Transport.h:132
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:694
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
uint32_t LinearFrameId
Definition MemProf.h:236
uint64_t CallStackId
Definition MemProf.h:353
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
void write32le(void *P, uint32_t V)
Definition Endian.h:455
uint32_t read32be(const void *P)
Definition Endian.h:421
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
void stable_sort(R &&Range)
Definition STLExtras.h:2132
StringMapEntry< Value * > ValueName
Definition Value.h:56
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
Definition Alignment.h:211
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ BWH_HeaderSize
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:966
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
#define NC
Definition regutils.h:42
#define NDEBUG
Definition regutils.h:48
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Definition Bitfields.h:223
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...