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;
1044 case Attribute::LikelyModuleLocal:
1047 llvm_unreachable("Can not encode end-attribute kinds marker.");
1048 case Attribute::None:
1049 llvm_unreachable("Can not encode none-attribute.");
1052 llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
1053 }
1054
1055 llvm_unreachable("Trying to encode unknown attribute");
1056}
1057
1059 if ((int64_t)V >= 0)
1060 Vals.push_back(V << 1);
1061 else
1062 Vals.push_back((-V << 1) | 1);
1063}
1064
1066 // We have an arbitrary precision integer value to write whose
1067 // bit width is > 64. However, in canonical unsigned integer
1068 // format it is likely that the high bits are going to be zero.
1069 // So, we only write the number of active words.
1070 unsigned NumWords = A.getActiveWords();
1071 const uint64_t *RawData = A.getRawData();
1072 for (unsigned i = 0; i < NumWords; i++)
1073 emitSignedInt64(Vals, RawData[i]);
1074}
1075
1077 const ConstantRange &CR, bool EmitBitWidth) {
1078 unsigned BitWidth = CR.getBitWidth();
1079 if (EmitBitWidth)
1080 Record.push_back(BitWidth);
1081 if (BitWidth > 64) {
1082 Record.push_back(CR.getLower().getActiveWords() |
1083 (uint64_t(CR.getUpper().getActiveWords()) << 32));
1086 } else {
1089 }
1090}
1091
1092void ModuleBitcodeWriter::writeAttributeGroupTable() {
1093 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1094 VE.getAttributeGroups();
1095 if (AttrGrps.empty()) return;
1096
1098
1099 SmallVector<uint64_t, 64> Record;
1100 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
1101 unsigned AttrListIndex = Pair.first;
1102 AttributeSet AS = Pair.second;
1103 Record.push_back(VE.getAttributeGroupID(Pair));
1104 Record.push_back(AttrListIndex);
1105
1106 for (Attribute Attr : AS) {
1107 if (Attr.isEnumAttribute()) {
1108 Record.push_back(0);
1109 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1110 } else if (Attr.isIntAttribute()) {
1111 Record.push_back(1);
1112 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1113 Record.push_back(getAttrKindEncoding(Kind));
1114 if (Kind == Attribute::Memory) {
1115 // Version field for upgrading old memory effects.
1116 const uint64_t Version = 2;
1117 Record.push_back((Version << 56) | Attr.getValueAsInt());
1118 } else {
1119 Record.push_back(Attr.getValueAsInt());
1120 }
1121 } else if (Attr.isStringAttribute()) {
1122 StringRef Kind = Attr.getKindAsString();
1123 StringRef Val = Attr.getValueAsString();
1124
1125 Record.push_back(Val.empty() ? 3 : 4);
1126 Record.append(Kind.begin(), Kind.end());
1127 Record.push_back(0);
1128 if (!Val.empty()) {
1129 Record.append(Val.begin(), Val.end());
1130 Record.push_back(0);
1131 }
1132 } else if (Attr.isTypeAttribute()) {
1133 Type *Ty = Attr.getValueAsType();
1134 Record.push_back(Ty ? 6 : 5);
1135 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1136 if (Ty)
1137 Record.push_back(VE.getTypeID(Attr.getValueAsType()));
1138 } else if (Attr.isConstantRangeAttribute()) {
1139 Record.push_back(7);
1140 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1141 emitConstantRange(Record, Attr.getValueAsConstantRange(),
1142 /*EmitBitWidth=*/true);
1143 } else {
1144 assert(Attr.isConstantRangeListAttribute());
1145 Record.push_back(8);
1146 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
1147 ArrayRef<ConstantRange> Val = Attr.getValueAsConstantRangeList();
1148 Record.push_back(Val.size());
1149 Record.push_back(Val[0].getBitWidth());
1150 for (auto &CR : Val)
1151 emitConstantRange(Record, CR, /*EmitBitWidth=*/false);
1152 }
1153 }
1154
1156 Record.clear();
1157 }
1158
1159 Stream.ExitBlock();
1160}
1161
1162void ModuleBitcodeWriter::writeAttributeTable() {
1163 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
1164 if (Attrs.empty()) return;
1165
1167
1168 SmallVector<uint64_t, 64> Record;
1169 for (const AttributeList &AL : Attrs) {
1170 for (unsigned i : AL.indexes()) {
1171 AttributeSet AS = AL.getAttributes(i);
1172 if (AS.hasAttributes())
1173 Record.push_back(VE.getAttributeGroupID({i, AS}));
1174 }
1175
1176 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
1177 Record.clear();
1178 }
1179
1180 Stream.ExitBlock();
1181}
1182
1183/// WriteTypeTable - Write out the type table for a module.
1184void ModuleBitcodeWriter::writeTypeTable() {
1185 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
1186
1187 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
1188 SmallVector<uint64_t, 64> TypeVals;
1189
1191
1192 // Abbrev for TYPE_CODE_OPAQUE_POINTER.
1193 auto Abbv = std::make_shared<BitCodeAbbrev>();
1194 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
1195 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
1196 unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1197
1198 // Abbrev for TYPE_CODE_FUNCTION.
1199 Abbv = std::make_shared<BitCodeAbbrev>();
1200 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
1201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
1202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1204 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1205
1206 // Abbrev for TYPE_CODE_STRUCT_ANON.
1207 Abbv = std::make_shared<BitCodeAbbrev>();
1208 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
1209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1212 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1213
1214 // Abbrev for TYPE_CODE_STRUCT_NAME.
1215 Abbv = std::make_shared<BitCodeAbbrev>();
1216 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
1217 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1219 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1220
1221 // Abbrev for TYPE_CODE_STRUCT_NAMED.
1222 Abbv = std::make_shared<BitCodeAbbrev>();
1223 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
1224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
1225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1227 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1228
1229 // Abbrev for TYPE_CODE_ARRAY.
1230 Abbv = std::make_shared<BitCodeAbbrev>();
1231 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
1232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1234 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1235
1236 // Emit an entry count so the reader can reserve space.
1237 TypeVals.push_back(TypeList.size());
1238 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1239 TypeVals.clear();
1240
1241 // Loop over all of the types, emitting each in turn.
1242 for (Type *T : TypeList) {
1243 int AbbrevToUse = 0;
1244 unsigned Code = 0;
1245
1246 switch (T->getTypeID()) {
1247 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
1248 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
1249 case Type::BFloatTyID: Code = bitc::TYPE_CODE_BFLOAT; break;
1250 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
1251 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
1252 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
1253 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
1254 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
1255 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
1256 case Type::MetadataTyID:
1258 break;
1259 case Type::X86_AMXTyID: Code = bitc::TYPE_CODE_X86_AMX; break;
1260 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
1261 case Type::ByteTyID:
1262 // BYTE: [width]
1264 TypeVals.push_back(T->getByteBitWidth());
1265 break;
1266 case Type::IntegerTyID:
1267 // INTEGER: [width]
1270 break;
1271 case Type::PointerTyID: {
1273 unsigned AddressSpace = PTy->getAddressSpace();
1274 // OPAQUE_POINTER: [address space]
1276 TypeVals.push_back(AddressSpace);
1277 if (AddressSpace == 0)
1278 AbbrevToUse = OpaquePtrAbbrev;
1279 break;
1280 }
1281 case Type::FunctionTyID: {
1282 FunctionType *FT = cast<FunctionType>(T);
1283 // FUNCTION: [isvararg, retty, paramty x N]
1285 TypeVals.push_back(FT->isVarArg());
1286 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
1287 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1288 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
1289 AbbrevToUse = FunctionAbbrev;
1290 break;
1291 }
1292 case Type::StructTyID: {
1293 StructType *ST = cast<StructType>(T);
1294 // STRUCT: [ispacked, eltty x N]
1295 TypeVals.push_back(ST->isPacked());
1296 // Output all of the element types.
1297 for (Type *ET : ST->elements())
1298 TypeVals.push_back(VE.getTypeID(ET));
1299
1300 if (ST->isLiteral()) {
1302 AbbrevToUse = StructAnonAbbrev;
1303 } else {
1304 if (ST->isOpaque()) {
1306 } else {
1308 AbbrevToUse = StructNamedAbbrev;
1309 }
1310
1311 // Emit the name if it is present.
1312 if (!ST->getName().empty())
1314 StructNameAbbrev);
1315 }
1316 break;
1317 }
1318 case Type::ArrayTyID: {
1320 // ARRAY: [numelts, eltty]
1322 TypeVals.push_back(AT->getNumElements());
1323 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1324 AbbrevToUse = ArrayAbbrev;
1325 break;
1326 }
1327 case Type::FixedVectorTyID:
1328 case Type::ScalableVectorTyID: {
1330 // VECTOR [numelts, eltty] or
1331 // [numelts, eltty, scalable]
1333 TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1334 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1336 TypeVals.push_back(true);
1337 break;
1338 }
1339 case Type::TargetExtTyID: {
1340 TargetExtType *TET = cast<TargetExtType>(T);
1343 StructNameAbbrev);
1344 TypeVals.push_back(TET->getNumTypeParameters());
1345 for (Type *InnerTy : TET->type_params())
1346 TypeVals.push_back(VE.getTypeID(InnerTy));
1347 llvm::append_range(TypeVals, TET->int_params());
1348 break;
1349 }
1350 case Type::TypedPointerTyID:
1351 llvm_unreachable("Typed pointers cannot be added to IR modules");
1352 }
1353
1354 // Emit the finished record.
1355 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1356 TypeVals.clear();
1357 }
1358
1359 Stream.ExitBlock();
1360}
1361
1363 switch (Linkage) {
1365 return 0;
1367 return 16;
1369 return 2;
1371 return 3;
1373 return 18;
1375 return 7;
1377 return 8;
1379 return 9;
1381 return 17;
1383 return 19;
1385 return 12;
1386 }
1387 llvm_unreachable("Invalid linkage");
1388}
1389
1390static unsigned getEncodedLinkage(const GlobalValue &GV) {
1391 return getEncodedLinkage(GV.getLinkage());
1392}
1393
1395 uint64_t RawFlags = 0;
1396 RawFlags |= Flags.ReadNone;
1397 RawFlags |= (Flags.ReadOnly << 1);
1398 RawFlags |= (Flags.NoRecurse << 2);
1399 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1400 RawFlags |= (Flags.NoInline << 4);
1401 RawFlags |= (Flags.AlwaysInline << 5);
1402 RawFlags |= (Flags.NoUnwind << 6);
1403 RawFlags |= (Flags.MayThrow << 7);
1404 RawFlags |= (Flags.HasUnknownCall << 8);
1405 RawFlags |= (Flags.MustBeUnreachable << 9);
1406 return RawFlags;
1407}
1408
1409// Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1410// in BitcodeReader.cpp.
1412 bool ImportAsDecl = false) {
1413 uint64_t RawFlags = 0;
1414
1415 RawFlags |= Flags.NotEligibleToImport; // bool
1416 RawFlags |= (Flags.Live << 1);
1417 RawFlags |= (Flags.DSOLocal << 2);
1418 RawFlags |= (Flags.CanAutoHide << 3);
1419
1420 // Linkage don't need to be remapped at that time for the summary. Any future
1421 // change to the getEncodedLinkage() function will need to be taken into
1422 // account here as well.
1423 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1424
1425 RawFlags |= (Flags.Visibility << 8); // 2 bits
1426
1427 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1428 RawFlags |= (ImportType << 10); // 1 bit
1429
1430 RawFlags |= (Flags.NoRenameOnPromotion << 11); // 1 bit
1431
1432 return RawFlags;
1433}
1434
1436 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1437 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1438 return RawFlags;
1439}
1440
1442 uint64_t RawFlags = 0;
1443
1444 RawFlags |= CI.Hotness; // 3 bits
1445 RawFlags |= (CI.HasTailCall << 3); // 1 bit
1446 RawFlags |= (CI.HasIndirectCall << 4); // 1 bit
1447
1448 return RawFlags;
1449}
1450
1451static unsigned getEncodedVisibility(const GlobalValue &GV) {
1452 switch (GV.getVisibility()) {
1453 case GlobalValue::DefaultVisibility: return 0;
1454 case GlobalValue::HiddenVisibility: return 1;
1455 case GlobalValue::ProtectedVisibility: return 2;
1456 }
1457 llvm_unreachable("Invalid visibility");
1458}
1459
1460static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1461 switch (GV.getDLLStorageClass()) {
1462 case GlobalValue::DefaultStorageClass: return 0;
1465 }
1466 llvm_unreachable("Invalid DLL storage class");
1467}
1468
1469static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1470 switch (GV.getThreadLocalMode()) {
1471 case GlobalVariable::NotThreadLocal: return 0;
1475 case GlobalVariable::LocalExecTLSModel: return 4;
1476 }
1477 llvm_unreachable("Invalid TLS model");
1478}
1479
1480static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1481 switch (C.getSelectionKind()) {
1482 case Comdat::Any:
1484 case Comdat::ExactMatch:
1486 case Comdat::Largest:
1490 case Comdat::SameSize:
1492 }
1493 llvm_unreachable("Invalid selection kind");
1494}
1495
1496static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1497 switch (GV.getUnnamedAddr()) {
1498 case GlobalValue::UnnamedAddr::None: return 0;
1499 case GlobalValue::UnnamedAddr::Local: return 2;
1500 case GlobalValue::UnnamedAddr::Global: return 1;
1501 }
1502 llvm_unreachable("Invalid unnamed_addr");
1503}
1504
1505size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1506 if (GenerateHash)
1507 Hasher.update(Str);
1508 return StrtabBuilder.add(Str);
1509}
1510
1511void ModuleBitcodeWriter::writeComdats() {
1513 for (const Comdat *C : VE.getComdats()) {
1514 // COMDAT: [strtab offset, strtab size, selection_kind]
1515 Vals.push_back(addToStrtab(C->getName()));
1516 Vals.push_back(C->getName().size());
1518 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1519 Vals.clear();
1520 }
1521}
1522
1523/// Write a record that will eventually hold the word offset of the
1524/// module-level VST. For now the offset is 0, which will be backpatched
1525/// after the real VST is written. Saves the bit offset to backpatch.
1526void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1527 // Write a placeholder value in for the offset of the real VST,
1528 // which is written after the function blocks so that it can include
1529 // the offset of each function. The placeholder offset will be
1530 // updated when the real VST is written.
1531 auto Abbv = std::make_shared<BitCodeAbbrev>();
1532 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1533 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1534 // hold the real VST offset. Must use fixed instead of VBR as we don't
1535 // know how many VBR chunks to reserve ahead of time.
1536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1537 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1538
1539 // Emit the placeholder
1541 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1542
1543 // Compute and save the bit offset to the placeholder, which will be
1544 // patched when the real VST is written. We can simply subtract the 32-bit
1545 // fixed size from the current bit number to get the location to backpatch.
1546 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1547}
1548
1550
1551/// Determine the encoding to use for the given string name and length.
1553 bool isChar6 = true;
1554 for (char C : Str) {
1555 if (isChar6)
1556 isChar6 = BitCodeAbbrevOp::isChar6(C);
1557 if ((unsigned char)C & 128)
1558 // don't bother scanning the rest.
1559 return SE_Fixed8;
1560 }
1561 if (isChar6)
1562 return SE_Char6;
1563 return SE_Fixed7;
1564}
1565
1566static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1567 "Sanitizer Metadata is too large for naive serialization.");
1568static unsigned
1570 return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1571 (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1572}
1573
1574/// Emit top-level description of module, including target triple, inline asm,
1575/// descriptors for global variables, and function prototype info.
1576/// Returns the bit offset to backpatch with the location of the real VST.
1577void ModuleBitcodeWriter::writeModuleInfo() {
1578 // Emit various pieces of data attached to a module.
1579 if (!M.getTargetTriple().empty())
1581 M.getTargetTriple().str(), 0 /*TODO*/);
1582 const std::string &DL = M.getDataLayoutStr();
1583 if (!DL.empty())
1585
1586 for (const Module::GlobalAsmFragment &Frag : M.getModuleInlineAsm()) {
1588 Frag.Props.getAsStrings();
1589 for (auto [Key, Value] : Props) {
1591 Record.append(Key.begin(), Key.end());
1592 Record.push_back(0);
1593 Record.append(Value.begin(), Value.end());
1595 }
1596 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, Frag.Asm, 0 /*TODO*/);
1597 }
1598
1599 // Emit information about sections and GC, computing how many there are. Also
1600 // compute the maximum alignment value.
1601 std::map<std::string, unsigned> SectionMap;
1602 std::map<std::string, unsigned> GCMap;
1603 MaybeAlign MaxGVarAlignment;
1604 unsigned MaxGlobalType = 0;
1605 for (const GlobalVariable &GV : M.globals()) {
1606 if (MaybeAlign A = GV.getAlign())
1607 MaxGVarAlignment = !MaxGVarAlignment ? *A : std::max(*MaxGVarAlignment, *A);
1608 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1609 if (GV.hasSection()) {
1610 // Give section names unique ID's.
1611 unsigned &Entry = SectionMap[std::string(GV.getSection())];
1612 if (!Entry) {
1613 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1614 0 /*TODO*/);
1615 Entry = SectionMap.size();
1616 }
1617 }
1618 }
1619 for (const Function &F : M) {
1620 if (F.hasSection()) {
1621 // Give section names unique ID's.
1622 unsigned &Entry = SectionMap[std::string(F.getSection())];
1623 if (!Entry) {
1625 0 /*TODO*/);
1626 Entry = SectionMap.size();
1627 }
1628 }
1629 if (F.hasGC()) {
1630 // Same for GC names.
1631 unsigned &Entry = GCMap[F.getGC()];
1632 if (!Entry) {
1634 0 /*TODO*/);
1635 Entry = GCMap.size();
1636 }
1637 }
1638 }
1639
1640 // Emit abbrev for globals, now that we know # sections and max alignment.
1641 unsigned SimpleGVarAbbrev = 0;
1642 if (!M.global_empty()) {
1643 // Add an abbrev for common globals with no visibility or thread localness.
1644 auto Abbv = std::make_shared<BitCodeAbbrev>();
1645 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1649 Log2_32_Ceil(MaxGlobalType+1)));
1650 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1651 //| explicitType << 1
1652 //| constant
1653 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1654 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1655 if (!MaxGVarAlignment) // Alignment.
1656 Abbv->Add(BitCodeAbbrevOp(0));
1657 else {
1658 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1660 Log2_32_Ceil(MaxEncAlignment+1)));
1661 }
1662 if (SectionMap.empty()) // Section.
1663 Abbv->Add(BitCodeAbbrevOp(0));
1664 else
1665 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1666 Log2_32_Ceil(SectionMap.size()+1)));
1667 // Don't bother emitting vis + thread local.
1668 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1669 }
1670
1672 // Emit the module's source file name.
1673 {
1674 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1675 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1676 if (Bits == SE_Char6)
1677 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1678 else if (Bits == SE_Fixed7)
1679 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1680
1681 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1682 auto Abbv = std::make_shared<BitCodeAbbrev>();
1683 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1684 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1685 Abbv->Add(AbbrevOpToUse);
1686 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1687
1688 for (const auto P : M.getSourceFileName())
1689 Vals.push_back((unsigned char)P);
1690
1691 // Emit the finished record.
1692 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1693 Vals.clear();
1694 }
1695
1696 writeGUIDList();
1697
1698 // Emit the global variable information.
1699 for (const GlobalVariable &GV : M.globals()) {
1700 unsigned AbbrevToUse = 0;
1701
1702 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1703 // linkage, alignment, section, visibility, threadlocal,
1704 // unnamed_addr, externally_initialized, dllstorageclass,
1705 // comdat, attributes, DSO_Local, GlobalSanitizer, code_model]
1706 Vals.push_back(addToStrtab(GV.getName()));
1707 Vals.push_back(GV.getName().size());
1708 Vals.push_back(VE.getTypeID(GV.getValueType()));
1709 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1710 Vals.push_back(GV.isDeclaration() ? 0 :
1711 (VE.getValueID(GV.getInitializer()) + 1));
1712 Vals.push_back(getEncodedLinkage(GV));
1713 Vals.push_back(getEncodedAlign(GV.getAlign()));
1714 Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1715 : 0);
1716 if (GV.isThreadLocal() ||
1717 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1718 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1719 GV.isExternallyInitialized() ||
1720 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1721 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1722 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1726 Vals.push_back(GV.isExternallyInitialized());
1728 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1729
1730 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1731 Vals.push_back(VE.getAttributeListID(AL));
1732
1733 Vals.push_back(GV.isDSOLocal());
1734 Vals.push_back(addToStrtab(GV.getPartition()));
1735 Vals.push_back(GV.getPartition().size());
1736
1737 Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1738 GV.getSanitizerMetadata())
1739 : 0));
1740 Vals.push_back(GV.getCodeModelRaw());
1741 } else {
1742 AbbrevToUse = SimpleGVarAbbrev;
1743 }
1744
1745 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1746 Vals.clear();
1747 }
1748
1749 // Emit the function proto information.
1750 for (const Function &F : M) {
1751 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1752 // linkage, paramattrs, alignment, section, visibility, gc,
1753 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1754 // prefixdata, personalityfn, DSO_Local, addrspace,
1755 // partition_strtab, partition_size, prefalign]
1756 Vals.push_back(addToStrtab(F.getName()));
1757 Vals.push_back(F.getName().size());
1758 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1759 Vals.push_back(F.getCallingConv());
1760 Vals.push_back(F.isDeclaration());
1762 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1763 Vals.push_back(getEncodedAlign(F.getAlign()));
1764 Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1765 : 0);
1767 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1769 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1770 : 0);
1772 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1773 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1774 : 0);
1775 Vals.push_back(
1776 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1777
1778 Vals.push_back(F.isDSOLocal());
1779 Vals.push_back(F.getAddressSpace());
1780 Vals.push_back(addToStrtab(F.getPartition()));
1781 Vals.push_back(F.getPartition().size());
1782 Vals.push_back(getEncodedAlign(F.getPreferredAlignment()));
1783
1784 unsigned AbbrevToUse = 0;
1785 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1786 Vals.clear();
1787 }
1788
1789 // Emit the alias information.
1790 for (const GlobalAlias &A : M.aliases()) {
1791 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1792 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1793 // DSO_Local]
1794 Vals.push_back(addToStrtab(A.getName()));
1795 Vals.push_back(A.getName().size());
1796 Vals.push_back(VE.getTypeID(A.getValueType()));
1797 Vals.push_back(A.getType()->getAddressSpace());
1798 Vals.push_back(VE.getValueID(A.getAliasee()));
1804 Vals.push_back(A.isDSOLocal());
1805 Vals.push_back(addToStrtab(A.getPartition()));
1806 Vals.push_back(A.getPartition().size());
1807
1808 unsigned AbbrevToUse = 0;
1809 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1810 Vals.clear();
1811 }
1812
1813 // Emit the ifunc information.
1814 for (const GlobalIFunc &I : M.ifuncs()) {
1815 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1816 // val#, linkage, visibility, DSO_Local]
1817 Vals.push_back(addToStrtab(I.getName()));
1818 Vals.push_back(I.getName().size());
1819 Vals.push_back(VE.getTypeID(I.getValueType()));
1820 Vals.push_back(I.getType()->getAddressSpace());
1821 Vals.push_back(VE.getValueID(I.getResolver()));
1824 Vals.push_back(I.isDSOLocal());
1825 Vals.push_back(addToStrtab(I.getPartition()));
1826 Vals.push_back(I.getPartition().size());
1827 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1828 Vals.clear();
1829 }
1830
1831 writeValueSymbolTableForwardDecl();
1832}
1833
1835 uint64_t Flags = 0;
1836
1837 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1838 if (OBO->hasNoSignedWrap())
1839 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1840 if (OBO->hasNoUnsignedWrap())
1841 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1842 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1843 if (PEO->isExact())
1844 Flags |= 1 << bitc::PEO_EXACT;
1845 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1846 if (PDI->isDisjoint())
1847 Flags |= 1 << bitc::PDI_DISJOINT;
1848 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1849 if (FPMO->hasAllowReassoc())
1850 Flags |= bitc::AllowReassoc;
1851 if (FPMO->hasNoNaNs())
1852 Flags |= bitc::NoNaNs;
1853 if (FPMO->hasNoInfs())
1854 Flags |= bitc::NoInfs;
1855 if (FPMO->hasNoSignedZeros())
1856 Flags |= bitc::NoSignedZeros;
1857 if (FPMO->hasAllowReciprocal())
1858 Flags |= bitc::AllowReciprocal;
1859 if (FPMO->hasAllowContract())
1860 Flags |= bitc::AllowContract;
1861 if (FPMO->hasApproxFunc())
1862 Flags |= bitc::ApproxFunc;
1863
1864 // Handle uitofp.
1865 if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1866 Flags <<= 1;
1867 if (NNI->hasNonNeg())
1868 Flags |= 1 << bitc::PNNI_NON_NEG;
1869 }
1870 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(V)) {
1871 if (NNI->hasNonNeg())
1872 Flags |= 1 << bitc::PNNI_NON_NEG;
1873 } else if (const auto *TI = dyn_cast<TruncInst>(V)) {
1874 if (TI->hasNoSignedWrap())
1875 Flags |= 1 << bitc::TIO_NO_SIGNED_WRAP;
1876 if (TI->hasNoUnsignedWrap())
1877 Flags |= 1 << bitc::TIO_NO_UNSIGNED_WRAP;
1878 } else if (const auto *GEP = dyn_cast<GEPOperator>(V)) {
1879 if (GEP->isInBounds())
1880 Flags |= 1 << bitc::GEP_INBOUNDS;
1881 if (GEP->hasNoUnsignedSignedWrap())
1882 Flags |= 1 << bitc::GEP_NUSW;
1883 if (GEP->hasNoUnsignedWrap())
1884 Flags |= 1 << bitc::GEP_NUW;
1885 } else if (const auto *ICmp = dyn_cast<ICmpInst>(V)) {
1886 if (ICmp->hasSameSign())
1887 Flags |= 1 << bitc::ICMP_SAME_SIGN;
1888 } else if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(V)) {
1889 if (ASC->hasNonNull())
1890 Flags |= 1 << bitc::ASCI_NON_NULL;
1891 }
1892
1893 return Flags;
1894}
1895
1896void ModuleBitcodeWriter::writeValueAsMetadata(
1897 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1898 // Mimic an MDNode with a value as one operand.
1899 Value *V = MD->getValue();
1900 Record.push_back(VE.getTypeID(V->getType()));
1901 Record.push_back(VE.getValueID(V));
1902 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1903 Record.clear();
1904}
1905
1906void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1907 SmallVectorImpl<uint64_t> &Record,
1908 unsigned Abbrev) {
1909 for (const MDOperand &MDO : N->operands()) {
1910 Metadata *MD = MDO;
1911 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1912 "Unexpected function-local metadata");
1913 Record.push_back(VE.getMetadataOrNullID(MD));
1914 }
1915 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1917 Record, Abbrev);
1918 Record.clear();
1919}
1920
1921unsigned ModuleBitcodeWriter::createDILocationAbbrev(bool WithIRLayers) {
1922 // Assume the column is usually under 128, and always output the inlined-at
1923 // location (it's never more expensive than building an array size 1).
1924 //
1925 // Separate abbrev so a location without layers does not spend a VBR chunk
1926 // encoding a zero; writeDILocation picks between the two per record.
1927 auto Abbv = std::make_shared<BitCodeAbbrev>();
1928 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isDistinct
1930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // line
1931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // column
1932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // scope
1933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // inlinedAt
1934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isImplicitCode
1935 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // atomGroup
1936 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // atomRank
1937 if (WithIRLayers)
1938 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // irlayers
1939 return Stream.EmitAbbrev(std::move(Abbv));
1940}
1941
1942void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1943 SmallVectorImpl<uint64_t> &Record,
1944 unsigned &Abbrev) {
1945 if (!Abbrev)
1946 Abbrev = createDILocationAbbrev(/*WithIRLayers=*/false);
1947
1948 Record.push_back(N->isDistinct());
1949 Record.push_back(N->getLine());
1950 Record.push_back(N->getColumn());
1951 Record.push_back(VE.getMetadataID(N->getScope()));
1952 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1953 Record.push_back(N->isImplicitCode());
1954 Record.push_back(N->getAtomGroup());
1955 Record.push_back(N->getAtomRank());
1956
1957 unsigned AbbrevToUse = Abbrev;
1958 if (DILayerLocList *IRLayers = N->getIRLayers()) {
1959 if (!DILocationLayersAbbrev)
1960 DILocationLayersAbbrev = createDILocationAbbrev(/*WithIRLayers=*/true);
1961 AbbrevToUse = DILocationLayersAbbrev;
1962 Record.push_back(VE.getMetadataOrNullID(IRLayers));
1963 }
1964
1965 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, AbbrevToUse);
1966 Record.clear();
1967}
1968
1969void ModuleBitcodeWriter::writeDILayerLoc(const DILayerLoc *N,
1970 SmallVectorImpl<uint64_t> &Record,
1971 unsigned Abbrev) {
1972 Record.push_back(N->isDistinct());
1973 Record.push_back(N->getLine());
1974 Record.push_back(N->getColumn());
1975 Record.push_back(VE.getMetadataID(N->getRawFile()));
1976 Record.push_back(VE.getMetadataID(N->getRawKind()));
1977 Stream.EmitRecord(bitc::METADATA_LAYERLOC, Record, Abbrev);
1978 Record.clear();
1979}
1980
1981void ModuleBitcodeWriter::writeDILayerLocList(const DILayerLocList *N,
1982 SmallVectorImpl<uint64_t> &Record,
1983 unsigned Abbrev) {
1984 Record.push_back(N->isDistinct());
1985 for (const MDOperand &Op : N->layers())
1986 Record.push_back(VE.getMetadataID(Op.get()));
1987 Stream.EmitRecord(bitc::METADATA_LAYERLOCLIST, Record, Abbrev);
1988 Record.clear();
1989}
1990
1991unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1992 // Assume the column is usually under 128, and always output the inlined-at
1993 // location (it's never more expensive than building an array size 1).
1994 auto Abbv = std::make_shared<BitCodeAbbrev>();
1995 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1997 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2002 return Stream.EmitAbbrev(std::move(Abbv));
2003}
2004
2005void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
2006 SmallVectorImpl<uint64_t> &Record,
2007 unsigned &Abbrev) {
2008 if (!Abbrev)
2009 Abbrev = createGenericDINodeAbbrev();
2010
2011 Record.push_back(N->isDistinct());
2012 Record.push_back(N->getTag());
2013 Record.push_back(0); // Per-tag version field; unused for now.
2014
2015 for (auto &I : N->operands())
2016 Record.push_back(VE.getMetadataOrNullID(I));
2017
2018 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
2019 Record.clear();
2020}
2021
2022void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
2023 SmallVectorImpl<uint64_t> &Record,
2024 unsigned Abbrev) {
2025 const uint64_t Version = 2 << 1;
2026 Record.push_back((uint64_t)N->isDistinct() | Version);
2027 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
2028 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2029 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2030 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2031
2032 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
2033 Record.clear();
2034}
2035
2036void ModuleBitcodeWriter::writeDIGenericSubrange(
2037 const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
2038 unsigned Abbrev) {
2039 Record.push_back((uint64_t)N->isDistinct());
2040 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
2041 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2042 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2043 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2044
2045 Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
2046 Record.clear();
2047}
2048
2049void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
2050 SmallVectorImpl<uint64_t> &Record,
2051 unsigned Abbrev) {
2052 const uint64_t IsBigInt = 1 << 2;
2053 Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
2054 Record.push_back(N->getValue().getBitWidth());
2055 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2056 emitWideAPInt(Record, N->getValue());
2057
2058 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
2059 Record.clear();
2060}
2061
2062void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
2063 SmallVectorImpl<uint64_t> &Record,
2064 unsigned Abbrev) {
2065 const unsigned SizeIsMetadata = 0x2;
2066 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2067 Record.push_back(N->getTag());
2068 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2069 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2070 Record.push_back(N->getAlignInBits());
2071 Record.push_back(N->getEncoding());
2072 Record.push_back(N->getFlags());
2073 Record.push_back(N->getNumExtraInhabitants());
2074 Record.push_back(N->getDataSizeInBits());
2075 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2076 Record.push_back(N->getLine());
2077 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2078
2079 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
2080 Record.clear();
2081}
2082
2083void ModuleBitcodeWriter::writeDIFixedPointType(
2084 const DIFixedPointType *N, SmallVectorImpl<uint64_t> &Record,
2085 unsigned Abbrev) {
2086 const unsigned SizeIsMetadata = 0x2;
2087 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2088 Record.push_back(N->getTag());
2089 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2090 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2091 Record.push_back(N->getAlignInBits());
2092 Record.push_back(N->getEncoding());
2093 Record.push_back(N->getFlags());
2094 Record.push_back(N->getKind());
2095 Record.push_back(N->getFactorRaw());
2096
2097 auto WriteWideInt = [&](const APInt &Value) {
2098 // Write an encoded word that holds the number of active words and
2099 // the number of bits.
2100 uint64_t NumWords = Value.getActiveWords();
2101 uint64_t Encoded = (NumWords << 32) | Value.getBitWidth();
2102 Record.push_back(Encoded);
2103 emitWideAPInt(Record, Value);
2104 };
2105
2106 WriteWideInt(N->getNumeratorRaw());
2107 WriteWideInt(N->getDenominatorRaw());
2108
2109 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2110 Record.push_back(N->getLine());
2111 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2112
2113 Stream.EmitRecord(bitc::METADATA_FIXED_POINT_TYPE, Record, Abbrev);
2114 Record.clear();
2115}
2116
2117void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
2118 SmallVectorImpl<uint64_t> &Record,
2119 unsigned Abbrev) {
2120 const unsigned SizeIsMetadata = 0x2;
2121 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2122 Record.push_back(N->getTag());
2123 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2124 Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
2125 Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
2126 Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
2127 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2128 Record.push_back(N->getAlignInBits());
2129 Record.push_back(N->getEncoding());
2130 Record.push_back(VE.getMetadataOrNullID(N->getRawCharType()));
2131
2132 Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
2133 Record.clear();
2134}
2135
2136void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
2137 SmallVectorImpl<uint64_t> &Record,
2138 unsigned Abbrev) {
2139 const unsigned SizeIsMetadata = 0x2;
2140 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2141 Record.push_back(N->getTag());
2142 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2143 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2144 Record.push_back(N->getLine());
2145 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2146 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2147 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2148 Record.push_back(N->getAlignInBits());
2149 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2150 Record.push_back(N->getFlags());
2151 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
2152
2153 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
2154 // that there is no DWARF address space associated with DIDerivedType.
2155 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2156 Record.push_back(*DWARFAddressSpace + 1);
2157 else
2158 Record.push_back(0);
2159
2160 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2161
2162 if (auto PtrAuthData = N->getPtrAuthData())
2163 Record.push_back(PtrAuthData->RawData);
2164 else
2165 Record.push_back(0);
2166
2167 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
2168 Record.clear();
2169}
2170
2171void ModuleBitcodeWriter::writeDISubrangeType(const DISubrangeType *N,
2172 SmallVectorImpl<uint64_t> &Record,
2173 unsigned Abbrev) {
2174 const unsigned SizeIsMetadata = 0x2;
2175 Record.push_back(SizeIsMetadata | (unsigned)N->isDistinct());
2176 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2177 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2178 Record.push_back(N->getLine());
2179 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2180 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2181 Record.push_back(N->getAlignInBits());
2182 Record.push_back(N->getFlags());
2183 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2184 Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
2185 Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
2186 Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
2187 Record.push_back(VE.getMetadataOrNullID(N->getRawBias()));
2188
2189 Stream.EmitRecord(bitc::METADATA_SUBRANGE_TYPE, Record, Abbrev);
2190 Record.clear();
2191}
2192
2193void ModuleBitcodeWriter::writeDICompositeType(
2194 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
2195 unsigned Abbrev) {
2196 const unsigned IsNotUsedInOldTypeRef = 0x2;
2197 const unsigned SizeIsMetadata = 0x4;
2198 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2199 (unsigned)N->isDistinct());
2200 Record.push_back(N->getTag());
2201 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2202 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2203 Record.push_back(N->getLine());
2204 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2205 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
2206 Record.push_back(VE.getMetadataOrNullID(N->getRawSizeInBits()));
2207 Record.push_back(N->getAlignInBits());
2208 Record.push_back(VE.getMetadataOrNullID(N->getRawOffsetInBits()));
2209 Record.push_back(N->getFlags());
2210 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2211 Record.push_back(N->getRuntimeLang());
2212 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
2213 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2214 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
2215 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
2216 Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
2217 Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
2218 Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
2219 Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
2220 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2221 Record.push_back(N->getNumExtraInhabitants());
2222 Record.push_back(VE.getMetadataOrNullID(N->getRawSpecification()));
2223 Record.push_back(
2224 N->getEnumKind().value_or(dwarf::DW_APPLE_ENUM_KIND_invalid));
2225 Record.push_back(VE.getMetadataOrNullID(N->getRawBitStride()));
2226
2227 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
2228 Record.clear();
2229}
2230
2231void ModuleBitcodeWriter::writeDISubroutineType(
2232 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
2233 unsigned Abbrev) {
2234 const unsigned HasNoOldTypeRefs = 0x2;
2235 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
2236 Record.push_back(N->getFlags());
2237 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
2238 Record.push_back(N->getCC());
2239
2240 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
2241 Record.clear();
2242}
2243
2244void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
2245 SmallVectorImpl<uint64_t> &Record,
2246 unsigned Abbrev) {
2247 Record.push_back(N->isDistinct());
2248 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
2249 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
2250 if (N->getRawChecksum()) {
2251 Record.push_back(N->getRawChecksum()->Kind);
2252 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
2253 } else {
2254 // Maintain backwards compatibility with the old internal representation of
2255 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
2256 Record.push_back(0);
2257 Record.push_back(VE.getMetadataOrNullID(nullptr));
2258 }
2259 auto Source = N->getRawSource();
2260 if (Source)
2261 Record.push_back(VE.getMetadataOrNullID(Source));
2262
2263 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
2264 Record.clear();
2265}
2266
2267void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
2268 SmallVectorImpl<uint64_t> &Record,
2269 unsigned Abbrev) {
2270 assert(N->isDistinct() && "Expected distinct compile units");
2271 Record.push_back(/* IsDistinct */ true);
2272
2273 auto Lang = N->getSourceLanguage();
2274 Record.push_back(Lang.getName());
2275 // Set bit so the MetadataLoader can distniguish between versioned and
2276 // unversioned names.
2277 if (Lang.hasVersionedName())
2278 Record.back() ^= (uint64_t(1) << 63);
2279
2280 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2281 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
2282 Record.push_back(N->isOptimized());
2283 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
2284 Record.push_back(N->getRuntimeVersion());
2285 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
2286 Record.push_back(N->getEmissionKind());
2287 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
2288 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
2289 Record.push_back(/* subprograms */ 0);
2290 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
2291 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
2292 Record.push_back(N->getDWOId());
2293 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
2294 Record.push_back(N->getSplitDebugInlining());
2295 Record.push_back(N->getDebugInfoForProfiling());
2296 Record.push_back((unsigned)N->getNameTableKind());
2297 Record.push_back(N->getRangesBaseAddress());
2298 Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
2299 Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
2300 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2301 Record.push_back(Lang.getDialect());
2302
2303 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
2304 Record.clear();
2305}
2306
2307void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
2308 SmallVectorImpl<uint64_t> &Record,
2309 unsigned Abbrev) {
2310 const uint64_t HasUnitFlag = 1 << 1;
2311 const uint64_t HasSPFlagsFlag = 1 << 2;
2312 Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2313 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2314 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2315 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2316 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2317 Record.push_back(N->getLine());
2318 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2319 Record.push_back(N->getScopeLine());
2320 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
2321 Record.push_back(N->getSPFlags());
2322 Record.push_back(N->getVirtualIndex());
2323 Record.push_back(N->getFlags());
2324 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
2325 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
2326 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
2327 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
2328 Record.push_back(N->getThisAdjustment());
2329 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
2330 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2331 Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
2332 Record.push_back(N->getKeyInstructionsEnabled());
2333
2334 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
2335 Record.clear();
2336}
2337
2338void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
2339 SmallVectorImpl<uint64_t> &Record,
2340 unsigned Abbrev) {
2341 Record.push_back(N->isDistinct());
2342 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2343 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2344 Record.push_back(N->getLine());
2345 Record.push_back(N->getColumn());
2346
2347 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
2348 Record.clear();
2349}
2350
2351void ModuleBitcodeWriter::writeDILexicalBlockFile(
2352 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
2353 unsigned Abbrev) {
2354 Record.push_back(N->isDistinct());
2355 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2356 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2357 Record.push_back(N->getDiscriminator());
2358
2359 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
2360 Record.clear();
2361}
2362
2363void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
2364 SmallVectorImpl<uint64_t> &Record,
2365 unsigned Abbrev) {
2366 Record.push_back(N->isDistinct());
2367 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2368 Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
2369 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2370 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2371 Record.push_back(N->getLineNo());
2372
2373 Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
2374 Record.clear();
2375}
2376
2377void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
2378 SmallVectorImpl<uint64_t> &Record,
2379 unsigned Abbrev) {
2380 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
2381 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2382 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2383
2384 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
2385 Record.clear();
2386}
2387
2388void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
2389 SmallVectorImpl<uint64_t> &Record,
2390 unsigned Abbrev) {
2391 Record.push_back(N->isDistinct());
2392 Record.push_back(N->getMacinfoType());
2393 Record.push_back(N->getLine());
2394 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2395 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
2396
2397 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
2398 Record.clear();
2399}
2400
2401void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
2402 SmallVectorImpl<uint64_t> &Record,
2403 unsigned Abbrev) {
2404 Record.push_back(N->isDistinct());
2405 Record.push_back(N->getMacinfoType());
2406 Record.push_back(N->getLine());
2407 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2408 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2409
2410 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
2411 Record.clear();
2412}
2413
2414void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
2415 SmallVectorImpl<uint64_t> &Record) {
2416 Record.reserve(N->getArgs().size());
2417 for (ValueAsMetadata *MD : N->getArgs())
2418 Record.push_back(VE.getMetadataID(MD));
2419
2420 Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record);
2421 Record.clear();
2422}
2423
2424void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
2425 SmallVectorImpl<uint64_t> &Record,
2426 unsigned Abbrev) {
2427 Record.push_back(N->isDistinct());
2428 for (auto &I : N->operands())
2429 Record.push_back(VE.getMetadataOrNullID(I));
2430 Record.push_back(N->getLineNo());
2431 Record.push_back(N->getIsDecl());
2432
2433 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
2434 Record.clear();
2435}
2436
2437void ModuleBitcodeWriter::writeDIAssignID(const DIAssignID *N,
2438 SmallVectorImpl<uint64_t> &Record,
2439 unsigned Abbrev) {
2440 // There are no arguments for this metadata type.
2441 Record.push_back(N->isDistinct());
2442 Stream.EmitRecord(bitc::METADATA_ASSIGN_ID, Record, Abbrev);
2443 Record.clear();
2444}
2445
2446void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2447 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
2448 unsigned Abbrev) {
2449 Record.push_back(N->isDistinct());
2450 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2451 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2452 Record.push_back(N->isDefault());
2453
2454 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
2455 Record.clear();
2456}
2457
2458void ModuleBitcodeWriter::writeDITemplateValueParameter(
2459 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
2460 unsigned Abbrev) {
2461 Record.push_back(N->isDistinct());
2462 Record.push_back(N->getTag());
2463 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2464 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2465 Record.push_back(N->isDefault());
2466 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
2467
2468 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
2469 Record.clear();
2470}
2471
2472void ModuleBitcodeWriter::writeDIGlobalVariable(
2473 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
2474 unsigned Abbrev) {
2475 const uint64_t Version = 2 << 1;
2476 Record.push_back((uint64_t)N->isDistinct() | Version);
2477 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2478 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2479 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
2480 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2481 Record.push_back(N->getLine());
2482 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2483 Record.push_back(N->isLocalToUnit());
2484 Record.push_back(N->isDefinition());
2485 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
2486 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
2487 Record.push_back(N->getAlignInBits());
2488 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2489
2490 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2491 Record.clear();
2492}
2493
2494void ModuleBitcodeWriter::writeDILocalVariable(
2495 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
2496 unsigned Abbrev) {
2497 // In order to support all possible bitcode formats in BitcodeReader we need
2498 // to distinguish the following cases:
2499 // 1) Record has no artificial tag (Record[1]),
2500 // has no obsolete inlinedAt field (Record[9]).
2501 // In this case Record size will be 8, HasAlignment flag is false.
2502 // 2) Record has artificial tag (Record[1]),
2503 // has no obsolete inlignedAt field (Record[9]).
2504 // In this case Record size will be 9, HasAlignment flag is false.
2505 // 3) Record has both artificial tag (Record[1]) and
2506 // obsolete inlignedAt field (Record[9]).
2507 // In this case Record size will be 10, HasAlignment flag is false.
2508 // 4) Record has neither artificial tag, nor inlignedAt field, but
2509 // HasAlignment flag is true and Record[8] contains alignment value.
2510 const uint64_t HasAlignmentFlag = 1 << 1;
2511 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2512 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2513 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2514 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2515 Record.push_back(N->getLine());
2516 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2517 Record.push_back(N->getArg());
2518 Record.push_back(N->getFlags());
2519 Record.push_back(N->getAlignInBits());
2520 Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2521
2522 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2523 Record.clear();
2524}
2525
2526void ModuleBitcodeWriter::writeDILabel(
2527 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2528 unsigned Abbrev) {
2529 uint64_t IsArtificialFlag = uint64_t(N->isArtificial()) << 1;
2530 Record.push_back((uint64_t)N->isDistinct() | IsArtificialFlag);
2531 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2532 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2533 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2534 Record.push_back(N->getLine());
2535 Record.push_back(N->getColumn());
2536 Record.push_back(N->getCoroSuspendIdx().has_value()
2537 ? (uint64_t)N->getCoroSuspendIdx().value()
2538 : std::numeric_limits<uint64_t>::max());
2539
2540 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2541 Record.clear();
2542}
2543
2544void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2545 SmallVectorImpl<uint64_t> &Record,
2546 unsigned Abbrev) {
2547 Record.reserve(N->getElements().size() + 1);
2548 const uint64_t Version = 3 << 1;
2549 Record.push_back((uint64_t)N->isDistinct() | Version);
2550 Record.append(N->elements_begin(), N->elements_end());
2551
2552 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2553 Record.clear();
2554}
2555
2556void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2557 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2558 unsigned Abbrev) {
2559 Record.push_back(N->isDistinct());
2560 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2561 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2562
2563 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2564 Record.clear();
2565}
2566
2567void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2568 SmallVectorImpl<uint64_t> &Record,
2569 unsigned Abbrev) {
2570 Record.push_back(N->isDistinct());
2571 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2572 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2573 Record.push_back(N->getLine());
2574 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2575 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2576 Record.push_back(N->getAttributes());
2577 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2578
2579 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2580 Record.clear();
2581}
2582
2583void ModuleBitcodeWriter::writeDIProperty(const DIProperty *N,
2584 SmallVectorImpl<uint64_t> &Record,
2585 unsigned Abbrev) {
2586 Record.push_back(N->isDistinct());
2587 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2588 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2589 Record.push_back(N->getLine());
2590 Record.push_back(VE.getMetadataOrNullID(N->getType()));
2591 Record.push_back(VE.getMetadataOrNullID(N->getBackingStorage()));
2592
2593 Stream.EmitRecord(bitc::METADATA_PROPERTY, Record, Abbrev);
2594 Record.clear();
2595}
2596
2597void ModuleBitcodeWriter::writeDIImportedEntity(
2598 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2599 unsigned Abbrev) {
2600 Record.push_back(N->isDistinct());
2601 Record.push_back(N->getTag());
2602 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2603 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2604 Record.push_back(N->getLine());
2605 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2606 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2607 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2608
2609 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2610 Record.clear();
2611}
2612
2613unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2614 auto Abbv = std::make_shared<BitCodeAbbrev>();
2615 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2617 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2618 return Stream.EmitAbbrev(std::move(Abbv));
2619}
2620
2621void ModuleBitcodeWriter::writeNamedMetadata(
2622 SmallVectorImpl<uint64_t> &Record) {
2623 if (M.named_metadata_empty())
2624 return;
2625
2626 unsigned Abbrev = createNamedMetadataAbbrev();
2627 for (const NamedMDNode &NMD : M.named_metadata()) {
2628 // Write name.
2629 StringRef Str = NMD.getName();
2630 Record.append(Str.bytes_begin(), Str.bytes_end());
2631 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2632 Record.clear();
2633
2634 // Write named metadata operands.
2635 for (const MDNode *N : NMD.operands())
2636 Record.push_back(VE.getMetadataID(N));
2637 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2638 Record.clear();
2639 }
2640}
2641
2642unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2643 auto Abbv = std::make_shared<BitCodeAbbrev>();
2644 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2648 return Stream.EmitAbbrev(std::move(Abbv));
2649}
2650
2651/// Write out a record for MDString.
2652///
2653/// All the metadata strings in a metadata block are emitted in a single
2654/// record. The sizes and strings themselves are shoved into a blob.
2655void ModuleBitcodeWriter::writeMetadataStrings(
2656 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2657 if (Strings.empty())
2658 return;
2659
2660 // Start the record with the number of strings.
2661 Record.push_back(bitc::METADATA_STRINGS);
2662 Record.push_back(Strings.size());
2663
2664 // Emit the sizes of the strings in the blob.
2665 SmallString<256> Blob;
2666 {
2667 BitstreamWriter W(Blob);
2668 for (const Metadata *MD : Strings)
2669 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2670 W.FlushToWord();
2671 }
2672
2673 // Add the offset to the strings to the record.
2674 Record.push_back(Blob.size());
2675
2676 // Add the strings to the blob.
2677 for (const Metadata *MD : Strings)
2678 Blob.append(cast<MDString>(MD)->getString());
2679
2680 // Emit the final record.
2681 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2682 Record.clear();
2683}
2684
2685// Generates an enum to use as an index in the Abbrev array of Metadata record.
2686enum MetadataAbbrev : unsigned {
2687#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2688#include "llvm/IR/Metadata.def"
2690};
2691
2692void ModuleBitcodeWriter::writeMetadataRecords(
2693 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2694 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2695 if (MDs.empty())
2696 return;
2697
2698 // Initialize MDNode abbreviations.
2699#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2700#include "llvm/IR/Metadata.def"
2701
2702 for (const Metadata *MD : MDs) {
2703 if (IndexPos)
2704 IndexPos->push_back(Stream.GetCurrentBitNo());
2705 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2706 assert(N->isResolved() && "Expected forward references to be resolved");
2707
2708 switch (N->getMetadataID()) {
2709 default:
2710 llvm_unreachable("Invalid MDNode subclass");
2711#define HANDLE_MDNODE_LEAF(CLASS) \
2712 case Metadata::CLASS##Kind: \
2713 if (MDAbbrevs) \
2714 write##CLASS(cast<CLASS>(N), Record, \
2715 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2716 else \
2717 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2718 continue;
2719#include "llvm/IR/Metadata.def"
2720 }
2721 }
2722 if (auto *AL = dyn_cast<DIArgList>(MD)) {
2724 continue;
2725 }
2726 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2727 }
2728}
2729
2730void ModuleBitcodeWriter::writeModuleMetadata() {
2731 if (!VE.hasMDs() && M.named_metadata_empty())
2732 return;
2733
2735 SmallVector<uint64_t, 64> Record;
2736
2737 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2738 // block and load any metadata.
2739 std::vector<unsigned> MDAbbrevs;
2740
2741 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2742 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2743 createDILocationAbbrev(/*WithIRLayers=*/false);
2744 DILocationLayersAbbrev = createDILocationAbbrev(/*WithIRLayers=*/true);
2745 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2746 createGenericDINodeAbbrev();
2747
2748 auto Abbv = std::make_shared<BitCodeAbbrev>();
2749 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2752 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2753
2754 Abbv = std::make_shared<BitCodeAbbrev>();
2755 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2756 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2757 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2758 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2759
2760 // Emit MDStrings together upfront.
2761 writeMetadataStrings(VE.getMDStrings(), Record);
2762
2763 // We only emit an index for the metadata record if we have more than a given
2764 // (naive) threshold of metadatas, otherwise it is not worth it.
2765 if (VE.getNonMDStrings().size() > IndexThreshold) {
2766 // Write a placeholder value in for the offset of the metadata index,
2767 // which is written after the records, so that it can include
2768 // the offset of each entry. The placeholder offset will be
2769 // updated after all records are emitted.
2770 uint64_t Vals[] = {0, 0};
2771 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2772 }
2773
2774 // Compute and save the bit offset to the current position, which will be
2775 // patched when we emit the index later. We can simply subtract the 64-bit
2776 // fixed size from the current bit number to get the location to backpatch.
2777 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2778
2779 // This index will contain the bitpos for each individual record.
2780 std::vector<uint64_t> IndexPos;
2781 IndexPos.reserve(VE.getNonMDStrings().size());
2782
2783 // Write all the records
2784 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2785
2786 if (VE.getNonMDStrings().size() > IndexThreshold) {
2787 // Now that we have emitted all the records we will emit the index. But
2788 // first
2789 // backpatch the forward reference so that the reader can skip the records
2790 // efficiently.
2791 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2792 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2793
2794 // Delta encode the index.
2795 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2796 for (auto &Elt : IndexPos) {
2797 auto EltDelta = Elt - PreviousValue;
2798 PreviousValue = Elt;
2799 Elt = EltDelta;
2800 }
2801 // Emit the index record.
2802 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2803 IndexPos.clear();
2804 }
2805
2806 // Write the named metadata now.
2807 writeNamedMetadata(Record);
2808
2809 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2810 SmallVector<uint64_t, 4> Record;
2811 Record.push_back(VE.getValueID(&GO));
2812 pushGlobalMetadataAttachment(Record, GO);
2814 };
2815 for (const Function &F : M)
2816 if (F.isDeclaration() && F.hasMetadata())
2817 AddDeclAttachedMetadata(F);
2818 for (const GlobalIFunc &GI : M.ifuncs())
2819 if (GI.hasMetadata())
2820 AddDeclAttachedMetadata(GI);
2821 // FIXME: Only store metadata for declarations here, and move data for global
2822 // variable definitions to a separate block (PR28134).
2823 for (const GlobalVariable &GV : M.globals())
2824 if (GV.hasMetadata())
2825 AddDeclAttachedMetadata(GV);
2826
2827 Stream.ExitBlock();
2828}
2829
2830void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2831 if (!VE.hasMDs())
2832 return;
2833
2835 // New block, new abbrev id space. Unlike the module block this one is not
2836 // randomly accessed, so the irlayers abbrev can be created on first use.
2837 DILocationLayersAbbrev = 0;
2838 SmallVector<uint64_t, 64> Record;
2839 writeMetadataStrings(VE.getMDStrings(), Record);
2840 writeMetadataRecords(VE.getNonMDStrings(), Record);
2841 Stream.ExitBlock();
2842}
2843
2844void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2845 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2846 // [n x [id, mdnode]]
2848 GO.getAllMetadata(MDs);
2849 for (const auto &I : MDs) {
2850 Record.push_back(I.first);
2851 Record.push_back(VE.getMetadataID(I.second));
2852 }
2853}
2854
2855void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2857
2858 SmallVector<uint64_t, 64> Record;
2859
2860 if (F.hasMetadata()) {
2861 pushGlobalMetadataAttachment(Record, F);
2862 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2863 Record.clear();
2864 }
2865
2866 // Write metadata attachments
2867 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2869 for (const BasicBlock &BB : F)
2870 for (const Instruction &I : BB) {
2871 MDs.clear();
2872 I.getAllMetadataOtherThanDebugLoc(MDs);
2873
2874 // If no metadata, ignore instruction.
2875 if (MDs.empty()) continue;
2876
2877 Record.push_back(VE.getInstructionID(&I));
2878
2879 for (const auto &[ID, MD] : MDs) {
2880 Record.push_back(ID);
2881 Record.push_back(VE.getMetadataID(MD));
2882 }
2883 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2884 Record.clear();
2885 }
2886
2887 Stream.ExitBlock();
2888}
2889
2890void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2891 SmallVector<uint64_t, 64> Record;
2892
2893 // Write metadata kinds
2894 // METADATA_KIND - [n x [id, name]]
2896 M.getMDKindNames(Names);
2897
2898 if (Names.empty()) return;
2899
2901
2902 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2903 Record.push_back(MDKindID);
2904 StringRef KName = Names[MDKindID];
2905 Record.append(KName.begin(), KName.end());
2906
2907 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2908 Record.clear();
2909 }
2910
2911 Stream.ExitBlock();
2912}
2913
2914void ModuleBitcodeWriter::writeOperandBundleTags() {
2915 // Write metadata kinds
2916 //
2917 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2918 //
2919 // OPERAND_BUNDLE_TAG - [strchr x N]
2920
2922 M.getOperandBundleTags(Tags);
2923
2924 if (Tags.empty())
2925 return;
2926
2928
2929 SmallVector<uint64_t, 64> Record;
2930
2931 for (auto Tag : Tags) {
2932 Record.append(Tag.begin(), Tag.end());
2933
2934 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2935 Record.clear();
2936 }
2937
2938 Stream.ExitBlock();
2939}
2940
2941void ModuleBitcodeWriter::writeSyncScopeNames() {
2943 M.getContext().getSyncScopeNames(SSNs);
2944 if (SSNs.empty())
2945 return;
2946
2948
2949 SmallVector<uint64_t, 64> Record;
2950 for (auto SSN : SSNs) {
2951 Record.append(SSN.begin(), SSN.end());
2952 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2953 Record.clear();
2954 }
2955
2956 Stream.ExitBlock();
2957}
2958
2959void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2960 bool isGlobal) {
2961 if (FirstVal == LastVal) return;
2962
2964
2965 unsigned AggregateAbbrev = 0;
2966 unsigned String8Abbrev = 0;
2967 unsigned CString7Abbrev = 0;
2968 unsigned CString6Abbrev = 0;
2969 // If this is a constant pool for the module, emit module-specific abbrevs.
2970 if (isGlobal) {
2971 // Abbrev for CST_CODE_AGGREGATE.
2972 auto Abbv = std::make_shared<BitCodeAbbrev>();
2973 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2976 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2977
2978 // Abbrev for CST_CODE_STRING.
2979 Abbv = std::make_shared<BitCodeAbbrev>();
2980 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2981 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2983 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2984 // Abbrev for CST_CODE_CSTRING.
2985 Abbv = std::make_shared<BitCodeAbbrev>();
2986 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2989 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2990 // Abbrev for CST_CODE_CSTRING.
2991 Abbv = std::make_shared<BitCodeAbbrev>();
2992 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2995 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2996 }
2997
2998 SmallVector<uint64_t, 64> Record;
2999
3000 const ValueEnumerator::ValueList &Vals = VE.getValues();
3001 Type *LastTy = nullptr;
3002 for (unsigned i = FirstVal; i != LastVal; ++i) {
3003 const Value *V = Vals[i].first;
3004 // If we need to switch types, do so now.
3005 if (V->getType() != LastTy) {
3006 LastTy = V->getType();
3007 Record.push_back(VE.getTypeID(LastTy));
3008 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
3009 CONSTANTS_SETTYPE_ABBREV);
3010 Record.clear();
3011 }
3012
3013 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
3014 Record.push_back(VE.getTypeID(IA->getFunctionType()));
3015 Record.push_back(
3016 unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
3017 unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
3018
3019 // Add the asm string.
3020 StringRef AsmStr = IA->getAsmString();
3021 Record.push_back(AsmStr.size());
3022 Record.append(AsmStr.begin(), AsmStr.end());
3023
3024 // Add the constraint string.
3025 StringRef ConstraintStr = IA->getConstraintString();
3026 Record.push_back(ConstraintStr.size());
3027 Record.append(ConstraintStr.begin(), ConstraintStr.end());
3028 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
3029 Record.clear();
3030 continue;
3031 }
3032 const Constant *C = cast<Constant>(V);
3033 unsigned Code = -1U;
3034 unsigned AbbrevToUse = 0;
3035 if (C->isNullValue()) {
3037 } else if (isa<PoisonValue>(C)) {
3039 } else if (isa<UndefValue>(C)) {
3041 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
3042 if (IV->getBitWidth() <= 64) {
3043 uint64_t V = IV->getSExtValue();
3044 emitSignedInt64(Record, V);
3046 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3047 } else { // Wide integers, > 64 bits in size.
3048 emitWideAPInt(Record, IV->getValue());
3050 }
3051 } else if (const ConstantByte *BV = dyn_cast<ConstantByte>(C)) {
3052 if (BV->getBitWidth() <= 64) {
3053 uint64_t V = BV->getSExtValue();
3054 emitSignedInt64(Record, V);
3056 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3057 } else { // Wide bytes, > 64 bits in size.
3058 emitWideAPInt(Record, BV->getValue());
3060 }
3061 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3063 Type *Ty = CFP->getType()->getScalarType();
3064 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
3065 Ty->isDoubleTy()) {
3066 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3067 } else if (Ty->isX86_FP80Ty()) {
3068 // api needed to prevent premature destruction
3069 // bits are not in the same order as a normal i80 APInt, compensate.
3070 APInt api = CFP->getValueAPF().bitcastToAPInt();
3071 const uint64_t *p = api.getRawData();
3072 Record.push_back((p[1] << 48) | (p[0] >> 16));
3073 Record.push_back(p[0] & 0xffffLL);
3074 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
3075 APInt api = CFP->getValueAPF().bitcastToAPInt();
3076 const uint64_t *p = api.getRawData();
3077 Record.push_back(p[0]);
3078 Record.push_back(p[1]);
3079 } else {
3080 assert(0 && "Unknown FP type!");
3081 }
3082 } else if (isa<ConstantDataSequential>(C) &&
3083 cast<ConstantDataSequential>(C)->isString()) {
3084 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
3085 // Emit constant strings specially.
3086 uint64_t NumElts = Str->getNumElements();
3087 // If this is a null-terminated string, use the denser CSTRING encoding.
3088 if (Str->isCString()) {
3090 --NumElts; // Don't encode the null, which isn't allowed by char6.
3091 } else {
3093 AbbrevToUse = String8Abbrev;
3094 }
3095 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
3096 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
3097 for (uint64_t i = 0; i != NumElts; ++i) {
3098 unsigned char V = Str->getElementAsInteger(i);
3099 Record.push_back(V);
3100 isCStr7 &= (V & 128) == 0;
3101 if (isCStrChar6)
3102 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
3103 }
3104
3105 if (isCStrChar6)
3106 AbbrevToUse = CString6Abbrev;
3107 else if (isCStr7)
3108 AbbrevToUse = CString7Abbrev;
3109 } else if (const ConstantDataSequential *CDS =
3112 Type *EltTy = CDS->getElementType();
3113 if (isa<IntegerType>(EltTy) || isa<ByteType>(EltTy)) {
3114 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3115 Record.push_back(CDS->getElementAsInteger(i));
3116 } else {
3117 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3118 Record.push_back(
3119 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3120 }
3121 } else if (isa<ConstantAggregate>(C)) {
3123 for (const Value *Op : C->operands())
3124 Record.push_back(VE.getValueID(Op));
3125 AbbrevToUse = AggregateAbbrev;
3126 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3127 switch (CE->getOpcode()) {
3128 default:
3129 if (Instruction::isCast(CE->getOpcode())) {
3131 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
3132 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3133 Record.push_back(VE.getValueID(C->getOperand(0)));
3134 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3135 } else {
3136 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
3138 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
3139 Record.push_back(VE.getValueID(C->getOperand(0)));
3140 Record.push_back(VE.getValueID(C->getOperand(1)));
3142 if (Flags != 0)
3143 Record.push_back(Flags);
3144 }
3145 break;
3146 case Instruction::GetElementPtr: {
3148 const auto *GO = cast<GEPOperator>(C);
3149 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
3150 Record.push_back(getOptimizationFlags(GO));
3151 if (std::optional<ConstantRange> Range = GO->getInRange()) {
3153 emitConstantRange(Record, *Range, /*EmitBitWidth=*/true);
3154 }
3155 for (const Value *Op : CE->operands()) {
3156 Record.push_back(VE.getTypeID(Op->getType()));
3157 Record.push_back(VE.getValueID(Op));
3158 }
3159 break;
3160 }
3161 case Instruction::ExtractElement:
3163 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3164 Record.push_back(VE.getValueID(C->getOperand(0)));
3165 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
3166 Record.push_back(VE.getValueID(C->getOperand(1)));
3167 break;
3168 case Instruction::InsertElement:
3170 Record.push_back(VE.getValueID(C->getOperand(0)));
3171 Record.push_back(VE.getValueID(C->getOperand(1)));
3172 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
3173 Record.push_back(VE.getValueID(C->getOperand(2)));
3174 break;
3175 case Instruction::ShuffleVector:
3176 // If the return type and argument types are the same, this is a
3177 // standard shufflevector instruction. If the types are different,
3178 // then the shuffle is widening or truncating the input vectors, and
3179 // the argument type must also be encoded.
3180 if (C->getType() == C->getOperand(0)->getType()) {
3182 } else {
3184 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
3185 }
3186 Record.push_back(VE.getValueID(C->getOperand(0)));
3187 Record.push_back(VE.getValueID(C->getOperand(1)));
3188 Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
3189 break;
3190 }
3191 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
3193 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
3194 Record.push_back(VE.getValueID(BA->getFunction()));
3195 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
3196 } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
3198 Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
3199 Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
3200 } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
3202 Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
3203 Record.push_back(VE.getValueID(NC->getGlobalValue()));
3204 } else if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C)) {
3206 Record.push_back(VE.getValueID(CPA->getPointer()));
3207 Record.push_back(VE.getValueID(CPA->getKey()));
3208 Record.push_back(VE.getValueID(CPA->getDiscriminator()));
3209 Record.push_back(VE.getValueID(CPA->getAddrDiscriminator()));
3210 Record.push_back(VE.getValueID(CPA->getDeactivationSymbol()));
3211 } else {
3212#ifndef NDEBUG
3213 C->dump();
3214#endif
3215 llvm_unreachable("Unknown constant!");
3216 }
3217 Stream.EmitRecord(Code, Record, AbbrevToUse);
3218 Record.clear();
3219 }
3220
3221 Stream.ExitBlock();
3222}
3223
3224void ModuleBitcodeWriter::writeModuleConstants() {
3225 const ValueEnumerator::ValueList &Vals = VE.getValues();
3226
3227 // Find the first constant to emit, which is the first non-globalvalue value.
3228 // We know globalvalues have been emitted by WriteModuleInfo.
3229 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
3230 if (!isa<GlobalValue>(Vals[i].first)) {
3231 writeConstants(i, Vals.size(), true);
3232 return;
3233 }
3234 }
3235}
3236
3237/// pushValueAndType - The file has to encode both the value and type id for
3238/// many values, because we need to know what type to create for forward
3239/// references. However, most operands are not forward references, so this type
3240/// field is not needed.
3241///
3242/// This function adds V's value ID to Vals. If the value ID is higher than the
3243/// instruction ID, then it is a forward reference, and it also includes the
3244/// type ID. The value ID that is written is encoded relative to the InstID.
3245bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
3246 SmallVectorImpl<unsigned> &Vals) {
3247 unsigned ValID = VE.getValueID(V);
3248 // Make encoding relative to the InstID.
3249 Vals.push_back(InstID - ValID);
3250 if (ValID >= InstID) {
3251 Vals.push_back(VE.getTypeID(V->getType()));
3252 return true;
3253 }
3254 return false;
3255}
3256
3257bool ModuleBitcodeWriter::pushValueOrMetadata(const Value *V, unsigned InstID,
3258 SmallVectorImpl<unsigned> &Vals) {
3259 bool IsMetadata = V->getType()->isMetadataTy();
3260 if (IsMetadata) {
3262 Metadata *MD = cast<MetadataAsValue>(V)->getMetadata();
3263 unsigned ValID = VE.getMetadataID(MD);
3264 Vals.push_back(InstID - ValID);
3265 return false;
3266 }
3267 return pushValueAndType(V, InstID, Vals);
3268}
3269
3270void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
3271 unsigned InstID) {
3273 LLVMContext &C = CS.getContext();
3274
3275 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
3276 const auto &Bundle = CS.getOperandBundleAt(i);
3277 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
3278
3279 for (auto &Input : Bundle.Inputs)
3280 pushValueOrMetadata(Input, InstID, Record);
3281
3283 Record.clear();
3284 }
3285}
3286
3287/// pushValue - Like pushValueAndType, but where the type of the value is
3288/// omitted (perhaps it was already encoded in an earlier operand).
3289void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
3290 SmallVectorImpl<unsigned> &Vals) {
3291 unsigned ValID = VE.getValueID(V);
3292 Vals.push_back(InstID - ValID);
3293}
3294
3295void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
3296 SmallVectorImpl<uint64_t> &Vals) {
3297 unsigned ValID = VE.getValueID(V);
3298 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3299 emitSignedInt64(Vals, diff);
3300}
3301
3302/// WriteInstruction - Emit an instruction to the specified stream.
3303void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
3304 unsigned InstID,
3305 SmallVectorImpl<unsigned> &Vals) {
3306 unsigned Code = 0;
3307 unsigned AbbrevToUse = 0;
3308 VE.setInstructionID(&I);
3309 switch (I.getOpcode()) {
3310 default:
3311 if (Instruction::isCast(I.getOpcode())) {
3313 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3314 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3315 Vals.push_back(VE.getTypeID(I.getType()));
3316 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
3318 if (Flags != 0) {
3319 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3320 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3321 Vals.push_back(Flags);
3322 }
3323 } else {
3324 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
3326 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3327 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3328 pushValue(I.getOperand(1), InstID, Vals);
3329 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
3331 if (Flags != 0) {
3332 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3333 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3334 Vals.push_back(Flags);
3335 }
3336 }
3337 break;
3338 case Instruction::FNeg: {
3340 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3341 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3342 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
3344 if (Flags != 0) {
3345 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3346 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3347 Vals.push_back(Flags);
3348 }
3349 break;
3350 }
3351 case Instruction::GetElementPtr: {
3353 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3354 auto &GEPInst = cast<GetElementPtrInst>(I);
3356 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
3357 for (const Value *Op : I.operands())
3358 pushValueAndType(Op, InstID, Vals);
3359 break;
3360 }
3361 case Instruction::ExtractValue: {
3363 pushValueAndType(I.getOperand(0), InstID, Vals);
3364 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3365 Vals.append(EVI->idx_begin(), EVI->idx_end());
3366 break;
3367 }
3368 case Instruction::InsertValue: {
3370 pushValueAndType(I.getOperand(0), InstID, Vals);
3371 pushValueAndType(I.getOperand(1), InstID, Vals);
3372 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
3373 Vals.append(IVI->idx_begin(), IVI->idx_end());
3374 break;
3375 }
3376 case Instruction::Select: {
3378 pushValueAndType(I.getOperand(1), InstID, Vals);
3379 pushValue(I.getOperand(2), InstID, Vals);
3380 pushValueAndType(I.getOperand(0), InstID, Vals);
3382 if (Flags != 0)
3383 Vals.push_back(Flags);
3384 break;
3385 }
3386 case Instruction::ExtractElement:
3388 pushValueAndType(I.getOperand(0), InstID, Vals);
3389 pushValueAndType(I.getOperand(1), InstID, Vals);
3390 break;
3391 case Instruction::InsertElement:
3393 pushValueAndType(I.getOperand(0), InstID, Vals);
3394 pushValue(I.getOperand(1), InstID, Vals);
3395 pushValueAndType(I.getOperand(2), InstID, Vals);
3396 break;
3397 case Instruction::BitExtract:
3399 Vals.push_back(VE.getTypeID(I.getType()));
3400 pushValueAndType(I.getOperand(0), InstID, Vals);
3401 pushValueAndType(I.getOperand(1), InstID, Vals);
3402 break;
3403 case Instruction::BitInsert:
3405 pushValueAndType(I.getOperand(0), InstID, Vals);
3406 pushValueAndType(I.getOperand(1), InstID, Vals);
3407 pushValueAndType(I.getOperand(2), InstID, Vals);
3408 break;
3409 case Instruction::ShuffleVector:
3411 pushValueAndType(I.getOperand(0), InstID, Vals);
3412 pushValue(I.getOperand(1), InstID, Vals);
3413 pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
3414 Vals);
3415 break;
3416 case Instruction::ICmp:
3417 case Instruction::FCmp: {
3418 // compare returning Int1Ty or vector of Int1Ty
3420 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3421 if (pushValueAndType(I.getOperand(0), InstID, Vals))
3422 AbbrevToUse = 0;
3423 pushValue(I.getOperand(1), InstID, Vals);
3426 if (Flags != 0) {
3427 Vals.push_back(Flags);
3428 if (AbbrevToUse)
3429 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3430 }
3431 break;
3432 }
3433
3434 case Instruction::Ret:
3435 {
3437 unsigned NumOperands = I.getNumOperands();
3438 if (NumOperands == 0)
3439 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3440 else if (NumOperands == 1) {
3441 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
3442 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3443 } else {
3444 for (const Value *Op : I.operands())
3445 pushValueAndType(Op, InstID, Vals);
3446 }
3447 }
3448 break;
3449 case Instruction::UncondBr: {
3451 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3452 const UncondBrInst &II = cast<UncondBrInst>(I);
3453 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3454 } break;
3455 case Instruction::CondBr: {
3457 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3458 const CondBrInst &II = cast<CondBrInst>(I);
3459 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
3460 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
3461 pushValue(II.getCondition(), InstID, Vals);
3462 } break;
3463 case Instruction::Switch:
3464 {
3466 const SwitchInst &SI = cast<SwitchInst>(I);
3467 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
3468 pushValue(SI.getCondition(), InstID, Vals);
3469 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
3470 for (auto Case : SI.cases()) {
3471 Vals.push_back(VE.getValueID(Case.getCaseValue()));
3472 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
3473 }
3474 }
3475 break;
3476 case Instruction::IndirectBr:
3478 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3479 // Encode the address operand as relative, but not the basic blocks.
3480 pushValue(I.getOperand(0), InstID, Vals);
3481 for (const Value *Op : drop_begin(I.operands()))
3482 Vals.push_back(VE.getValueID(Op));
3483 break;
3484
3485 case Instruction::Invoke: {
3486 const InvokeInst *II = cast<InvokeInst>(&I);
3487 const Value *Callee = II->getCalledOperand();
3488 FunctionType *FTy = II->getFunctionType();
3489
3490 if (II->hasOperandBundles())
3491 writeOperandBundles(*II, InstID);
3492
3494
3495 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
3496 Vals.push_back(II->getCallingConv() | 1 << 13);
3497 Vals.push_back(VE.getValueID(II->getNormalDest()));
3498 Vals.push_back(VE.getValueID(II->getUnwindDest()));
3499 Vals.push_back(VE.getTypeID(FTy));
3500 pushValueAndType(Callee, InstID, Vals);
3501
3502 // Emit value #'s for the fixed parameters.
3503 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3504 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3505
3506 // Emit type/value pairs for varargs params.
3507 if (FTy->isVarArg()) {
3508 for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
3509 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3510 }
3511 break;
3512 }
3513 case Instruction::Resume:
3515 pushValueAndType(I.getOperand(0), InstID, Vals);
3516 break;
3517 case Instruction::CleanupRet: {
3519 const auto &CRI = cast<CleanupReturnInst>(I);
3520 pushValue(CRI.getCleanupPad(), InstID, Vals);
3521 if (CRI.hasUnwindDest())
3522 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
3523 break;
3524 }
3525 case Instruction::CatchRet: {
3527 const auto &CRI = cast<CatchReturnInst>(I);
3528 pushValue(CRI.getCatchPad(), InstID, Vals);
3529 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
3530 break;
3531 }
3532 case Instruction::CleanupPad:
3533 case Instruction::CatchPad: {
3534 const auto &FuncletPad = cast<FuncletPadInst>(I);
3537 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3538
3539 unsigned NumArgOperands = FuncletPad.arg_size();
3540 Vals.push_back(NumArgOperands);
3541 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
3542 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
3543 break;
3544 }
3545 case Instruction::CatchSwitch: {
3547 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
3548
3549 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3550
3551 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3552 Vals.push_back(NumHandlers);
3553 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3554 Vals.push_back(VE.getValueID(CatchPadBB));
3555
3556 if (CatchSwitch.hasUnwindDest())
3557 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3558 break;
3559 }
3560 case Instruction::CallBr: {
3561 const CallBrInst *CBI = cast<CallBrInst>(&I);
3562 const Value *Callee = CBI->getCalledOperand();
3563 FunctionType *FTy = CBI->getFunctionType();
3564
3565 if (CBI->hasOperandBundles())
3566 writeOperandBundles(*CBI, InstID);
3567
3569
3571
3574
3575 Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3576 Vals.push_back(CBI->getNumIndirectDests());
3577 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3578 Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3579
3580 Vals.push_back(VE.getTypeID(FTy));
3581 pushValueAndType(Callee, InstID, Vals);
3582
3583 // Emit value #'s for the fixed parameters.
3584 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3585 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3586
3587 // Emit type/value pairs for varargs params.
3588 if (FTy->isVarArg()) {
3589 for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3590 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3591 }
3592 break;
3593 }
3594 case Instruction::Unreachable:
3596 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3597 break;
3598
3599 case Instruction::PHI: {
3600 const PHINode &PN = cast<PHINode>(I);
3602 // With the newer instruction encoding, forward references could give
3603 // negative valued IDs. This is most common for PHIs, so we use
3604 // signed VBRs.
3606 Vals64.push_back(VE.getTypeID(PN.getType()));
3607 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3608 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3609 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3610 }
3611
3613 if (Flags != 0)
3614 Vals64.push_back(Flags);
3615
3616 // Emit a Vals64 vector and exit.
3617 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3618 Vals64.clear();
3619 return;
3620 }
3621
3622 case Instruction::LandingPad: {
3623 const LandingPadInst &LP = cast<LandingPadInst>(I);
3625 Vals.push_back(VE.getTypeID(LP.getType()));
3626 Vals.push_back(LP.isCleanup());
3627 Vals.push_back(LP.getNumClauses());
3628 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3629 if (LP.isCatch(I))
3631 else
3633 pushValueAndType(LP.getClause(I), InstID, Vals);
3634 }
3635 break;
3636 }
3637
3638 case Instruction::Alloca: {
3640 const AllocaInst &AI = cast<AllocaInst>(I);
3641 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3642 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3643 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3644 using APV = AllocaPackedValues;
3645 unsigned Record = 0;
3646 unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3648 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3650 EncodedAlign >> APV::AlignLower::Bits);
3654 Vals.push_back(Record);
3655
3656 unsigned AS = AI.getAddressSpace();
3657 if (AS != M.getDataLayout().getAllocaAddrSpace())
3658 Vals.push_back(AS);
3659 break;
3660 }
3661
3662 case Instruction::Load: {
3663 const auto &LI = cast<LoadInst>(I);
3664 if (LI.isAtomic()) {
3666 pushValueAndType(LI.getOperand(0), InstID, Vals);
3667 } else {
3669 if (!pushValueAndType(LI.getOperand(0), InstID, Vals)) // ptr
3670 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3671 }
3672 Vals.push_back(VE.getTypeID(LI.getType()));
3673 Vals.push_back(getEncodedAlign(LI.getAlign()));
3674 Vals.push_back(LI.isVolatile());
3675 if (LI.isAtomic()) {
3676 Vals.push_back(getEncodedOrdering(LI.getOrdering()));
3677 Vals.push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3678 if (LI.isElementwise())
3679 Vals.push_back(1);
3680 }
3681 break;
3682 }
3683
3684 case Instruction::Store: {
3685 const auto &SI = cast<StoreInst>(I);
3686 if (SI.isAtomic()) {
3688 } else {
3690 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3691 }
3692 if (pushValueAndType(I.getOperand(1), InstID, Vals)) // ptrty + ptr
3693 AbbrevToUse = 0;
3694 if (pushValueAndType(I.getOperand(0), InstID, Vals)) // valty + val
3695 AbbrevToUse = 0;
3696 Vals.push_back(getEncodedAlign(SI.getAlign()));
3697 Vals.push_back(SI.isVolatile());
3698 if (SI.isAtomic()) {
3699 Vals.push_back(getEncodedOrdering(SI.getOrdering()));
3700 Vals.push_back(getEncodedSyncScopeID(SI.getSyncScopeID()));
3701 if (SI.isElementwise())
3702 Vals.push_back(1);
3703 }
3704 break;
3705 }
3706
3707 case Instruction::AtomicCmpXchg:
3709 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3710 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3711 pushValue(I.getOperand(2), InstID, Vals); // newval.
3712 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3713 Vals.push_back(
3714 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3715 Vals.push_back(
3716 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3717 Vals.push_back(
3718 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3719 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3720 Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3721 break;
3722 case Instruction::AtomicRMW:
3724 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3725 pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3727 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3728 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3729 Vals.push_back(
3730 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3731 Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3732 break;
3733 case Instruction::Fence:
3735 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3736 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3737 break;
3738 case Instruction::Call: {
3739 const CallInst &CI = cast<CallInst>(I);
3740 FunctionType *FTy = CI.getFunctionType();
3741
3742 if (CI.hasOperandBundles())
3743 writeOperandBundles(CI, InstID);
3744
3746
3748
3749 unsigned Flags = getOptimizationFlags(&I);
3751 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3752 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3754 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3755 unsigned(Flags != 0) << bitc::CALL_FMF);
3756 if (Flags != 0)
3757 Vals.push_back(Flags);
3758
3759 Vals.push_back(VE.getTypeID(FTy));
3760 pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3761
3762 // Emit value #'s for the fixed parameters.
3763 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3764 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3765
3766 // Emit type/value pairs for varargs params.
3767 if (FTy->isVarArg()) {
3768 for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3769 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3770 }
3771 break;
3772 }
3773 case Instruction::VAArg:
3775 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3776 pushValue(I.getOperand(0), InstID, Vals); // valist.
3777 Vals.push_back(VE.getTypeID(I.getType())); // restype.
3778 break;
3779 case Instruction::Freeze:
3781 pushValueAndType(I.getOperand(0), InstID, Vals);
3782 break;
3783 }
3784
3785 Stream.EmitRecord(Code, Vals, AbbrevToUse);
3786 Vals.clear();
3787}
3788
3789/// Write a GlobalValue VST to the module. The purpose of this data structure is
3790/// to allow clients to efficiently find the function body.
3791void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3792 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3793 // Get the offset of the VST we are writing, and backpatch it into
3794 // the VST forward declaration record.
3795 uint64_t VSTOffset = Stream.GetCurrentBitNo();
3796 // The BitcodeStartBit was the stream offset of the identification block.
3797 VSTOffset -= bitcodeStartBit();
3798 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3799 // Note that we add 1 here because the offset is relative to one word
3800 // before the start of the identification block, which was historically
3801 // always the start of the regular bitcode header.
3802 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3803
3805
3806 auto Abbv = std::make_shared<BitCodeAbbrev>();
3807 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3810 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3811
3812 for (const Function &F : M) {
3813 uint64_t Record[2];
3814
3815 if (F.isDeclaration())
3816 continue;
3817
3818 Record[0] = VE.getValueID(&F);
3819
3820 // Save the word offset of the function (from the start of the
3821 // actual bitcode written to the stream).
3822 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3823 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3824 // Note that we add 1 here because the offset is relative to one word
3825 // before the start of the identification block, which was historically
3826 // always the start of the regular bitcode header.
3827 Record[1] = BitcodeIndex / 32 + 1;
3828
3829 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3830 }
3831
3832 Stream.ExitBlock();
3833}
3834
3835/// Emit names for arguments, instructions and basic blocks in a function.
3836void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3837 const ValueSymbolTable &VST) {
3838 if (VST.empty())
3839 return;
3840
3842
3843 // FIXME: Set up the abbrev, we know how many values there are!
3844 // FIXME: We know if the type names can use 7-bit ascii.
3845 SmallVector<uint64_t, 64> NameVals;
3846
3847 for (const ValueName &Name : VST) {
3848 // Figure out the encoding to use for the name.
3850
3851 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3852 NameVals.push_back(VE.getValueID(Name.getValue()));
3853
3854 // VST_CODE_ENTRY: [valueid, namechar x N]
3855 // VST_CODE_BBENTRY: [bbid, namechar x N]
3856 unsigned Code;
3857 if (isa<BasicBlock>(Name.getValue())) {
3859 if (Bits == SE_Char6)
3860 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3861 } else {
3863 if (Bits == SE_Char6)
3864 AbbrevToUse = VST_ENTRY_6_ABBREV;
3865 else if (Bits == SE_Fixed7)
3866 AbbrevToUse = VST_ENTRY_7_ABBREV;
3867 }
3868
3869 for (const auto P : Name.getKey())
3870 NameVals.push_back((unsigned char)P);
3871
3872 // Emit the finished record.
3873 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3874 NameVals.clear();
3875 }
3876
3877 Stream.ExitBlock();
3878}
3879
3880void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3881 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3882 unsigned Code;
3883 if (isa<BasicBlock>(Order.V))
3885 else
3887
3888 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3889 Record.push_back(VE.getValueID(Order.V));
3890 Stream.EmitRecord(Code, Record);
3891}
3892
3893void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3895 "Expected to be preserving use-list order");
3896
3897 auto hasMore = [&]() {
3898 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3899 };
3900 if (!hasMore())
3901 // Nothing to do.
3902 return;
3903
3905 while (hasMore()) {
3906 writeUseList(std::move(VE.UseListOrders.back()));
3907 VE.UseListOrders.pop_back();
3908 }
3909 Stream.ExitBlock();
3910}
3911
3912/// Emit a function body to the module stream.
3913void ModuleBitcodeWriter::writeFunction(
3914 const Function &F,
3915 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3916 // Save the bitcode index of the start of this function block for recording
3917 // in the VST.
3918 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3919
3922
3924
3925 // Emit the number of basic blocks, so the reader can create them ahead of
3926 // time.
3927 Vals.push_back(VE.getBasicBlocks().size());
3929 Vals.clear();
3930
3931 // If there are function-local constants, emit them now.
3932 unsigned CstStart, CstEnd;
3933 VE.getFunctionConstantRange(CstStart, CstEnd);
3934 writeConstants(CstStart, CstEnd, false);
3935
3936 // If there is function-local metadata, emit it now.
3937 writeFunctionMetadata(F);
3938
3939 // Keep a running idea of what the instruction ID is.
3940 unsigned InstID = CstEnd;
3941
3942 bool NeedsMetadataAttachment = F.hasMetadata();
3943
3944 DILocation *LastDL = nullptr;
3945 SmallSetVector<Function *, 4> BlockAddressUsers;
3946
3947 // Finally, emit all the instructions, in order.
3948 for (const BasicBlock &BB : F) {
3949 for (const Instruction &I : BB) {
3950 writeInstruction(I, InstID, Vals);
3951
3952 if (!I.getType()->isVoidTy())
3953 ++InstID;
3954
3955 // If the instruction has metadata, write a metadata attachment later.
3956 NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3957
3958 // If the instruction has a debug location, emit it.
3959 if (DILocation *DL = I.getDebugLoc()) {
3960 if (DL == LastDL) {
3961 // Just repeat the same debug loc as last time.
3963 } else {
3964 Vals.push_back(DL->getLine());
3965 Vals.push_back(DL->getColumn());
3966 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3967 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3968 Vals.push_back(DL->isImplicitCode());
3969 Vals.push_back(DL->getAtomGroup());
3970 Vals.push_back(DL->getAtomRank());
3971
3972 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3973 if (DILayerLocList *IRLayers = DL->getIRLayers()) {
3974 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3975 Vals.push_back(VE.getMetadataOrNullID(IRLayers));
3976 }
3977
3978 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals, DLAbbrev);
3979 Vals.clear();
3980 LastDL = DL;
3981 }
3982 }
3983
3984 // If the instruction has DbgRecords attached to it, emit them. Note that
3985 // they come after the instruction so that it's easy to attach them again
3986 // when reading the bitcode, even though conceptually the debug locations
3987 // start "before" the instruction.
3988 if (I.hasDbgRecords()) {
3989 /// Try to push the value only (unwrapped), otherwise push the
3990 /// metadata wrapped value. Returns true if the value was pushed
3991 /// without the ValueAsMetadata wrapper.
3992 auto PushValueOrMetadata = [&Vals, InstID,
3993 this](Metadata *RawLocation) {
3994 assert(RawLocation &&
3995 "RawLocation unexpectedly null in DbgVariableRecord");
3996 if (ValueAsMetadata *VAM = dyn_cast<ValueAsMetadata>(RawLocation)) {
3997 SmallVector<unsigned, 2> ValAndType;
3998 // If the value is a fwd-ref the type is also pushed. We don't
3999 // want the type, so fwd-refs are kept wrapped (pushValueAndType
4000 // returns false if the value is pushed without type).
4001 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4002 Vals.push_back(ValAndType[0]);
4003 return true;
4004 }
4005 }
4006 // The metadata is a DIArgList, or ValueAsMetadata wrapping a
4007 // fwd-ref. Push the metadata ID.
4008 Vals.push_back(VE.getMetadataID(RawLocation));
4009 return false;
4010 };
4011
4012 // Write out non-instruction debug information attached to this
4013 // instruction. Write it after the instruction so that it's easy to
4014 // re-attach to the instruction reading the records in.
4015 for (DbgRecord &DR : I.getDbgMarker()->getDbgRecordRange()) {
4016 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
4017 Vals.push_back(VE.getMetadataID(&*DLR->getDebugLoc()));
4018 Vals.push_back(VE.getMetadataID(DLR->getLabel()));
4020 Vals.clear();
4021 continue;
4022 }
4023
4024 // First 3 fields are common to all kinds:
4025 // DILocation, DILocalVariable, DIExpression
4026 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
4027 // ..., LocationMetadata
4028 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
4029 // ..., Value
4030 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
4031 // ..., LocationMetadata
4032 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
4033 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
4034 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
4035 Vals.push_back(VE.getMetadataID(&*DVR.getDebugLoc()));
4036 Vals.push_back(VE.getMetadataID(DVR.getVariable()));
4037 Vals.push_back(VE.getMetadataID(DVR.getExpression()));
4038 if (DVR.isDbgValue()) {
4039 if (PushValueOrMetadata(DVR.getRawLocation()))
4041 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4042 else
4044 } else if (DVR.isDbgDeclare()) {
4045 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4047 } else if (DVR.isDbgDeclareValue()) {
4048 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4050 } else {
4051 assert(DVR.isDbgAssign() && "Unexpected DbgRecord kind");
4052 Vals.push_back(VE.getMetadataID(DVR.getRawLocation()));
4053 Vals.push_back(VE.getMetadataID(DVR.getAssignID()));
4055 Vals.push_back(VE.getMetadataID(DVR.getRawAddress()));
4057 }
4058 Vals.clear();
4059 }
4060 }
4061 }
4062
4063 if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
4064 SmallVector<Value *> Worklist{BA};
4065 SmallPtrSet<Value *, 8> Visited{BA};
4066 while (!Worklist.empty()) {
4067 Value *V = Worklist.pop_back_val();
4068 for (User *U : V->users()) {
4069 if (auto *I = dyn_cast<Instruction>(U)) {
4070 Function *P = I->getFunction();
4071 if (P != &F)
4072 BlockAddressUsers.insert(P);
4073 } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
4074 Visited.insert(U).second)
4075 Worklist.push_back(U);
4076 }
4077 }
4078 }
4079 }
4080
4081 if (!BlockAddressUsers.empty()) {
4082 Vals.resize(BlockAddressUsers.size());
4083 for (auto I : llvm::enumerate(BlockAddressUsers))
4084 Vals[I.index()] = VE.getValueID(I.value());
4086 Vals.clear();
4087 }
4088
4089 // Emit names for all the instructions etc.
4090 if (auto *Symtab = F.getValueSymbolTable())
4091 writeFunctionLevelValueSymbolTable(*Symtab);
4092
4093 if (NeedsMetadataAttachment)
4094 writeFunctionMetadataAttachment(F);
4096 writeUseListBlock(&F);
4097 VE.purgeFunction();
4098 Stream.ExitBlock();
4099}
4100
4101// Emit blockinfo, which defines the standard abbreviations etc.
4102void ModuleBitcodeWriter::writeBlockInfo() {
4103 // We only want to emit block info records for blocks that have multiple
4104 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
4105 // Other blocks can define their abbrevs inline.
4106 Stream.EnterBlockInfoBlock();
4107
4108 // Encode type indices using fixed size based on number of types.
4109 BitCodeAbbrevOp TypeAbbrevOp(BitCodeAbbrevOp::Fixed,
4111 // Encode value indices as 6-bit VBR.
4112 BitCodeAbbrevOp ValAbbrevOp(BitCodeAbbrevOp::VBR, 6);
4113
4114 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
4115 auto Abbv = std::make_shared<BitCodeAbbrev>();
4116 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
4117 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4118 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4119 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4121 VST_ENTRY_8_ABBREV)
4122 llvm_unreachable("Unexpected abbrev ordering!");
4123 }
4124
4125 { // 7-bit fixed width VST_CODE_ENTRY strings.
4126 auto Abbv = std::make_shared<BitCodeAbbrev>();
4127 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4132 VST_ENTRY_7_ABBREV)
4133 llvm_unreachable("Unexpected abbrev ordering!");
4134 }
4135 { // 6-bit char6 VST_CODE_ENTRY strings.
4136 auto Abbv = std::make_shared<BitCodeAbbrev>();
4137 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
4138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4142 VST_ENTRY_6_ABBREV)
4143 llvm_unreachable("Unexpected abbrev ordering!");
4144 }
4145 { // 6-bit char6 VST_CODE_BBENTRY strings.
4146 auto Abbv = std::make_shared<BitCodeAbbrev>();
4147 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
4148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4152 VST_BBENTRY_6_ABBREV)
4153 llvm_unreachable("Unexpected abbrev ordering!");
4154 }
4155
4156 { // SETTYPE abbrev for CONSTANTS_BLOCK.
4157 auto Abbv = std::make_shared<BitCodeAbbrev>();
4158 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
4159 Abbv->Add(TypeAbbrevOp);
4161 CONSTANTS_SETTYPE_ABBREV)
4162 llvm_unreachable("Unexpected abbrev ordering!");
4163 }
4164
4165 { // INTEGER abbrev for CONSTANTS_BLOCK.
4166 auto Abbv = std::make_shared<BitCodeAbbrev>();
4167 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
4168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4170 CONSTANTS_INTEGER_ABBREV)
4171 llvm_unreachable("Unexpected abbrev ordering!");
4172 }
4173
4174 { // BYTE abbrev for CONSTANTS_BLOCK.
4175 auto Abbv = std::make_shared<BitCodeAbbrev>();
4176 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_BYTE));
4177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4179 CONSTANTS_BYTE_ABBREV)
4180 llvm_unreachable("Unexpected abbrev ordering!");
4181 }
4182
4183 { // CE_CAST abbrev for CONSTANTS_BLOCK.
4184 auto Abbv = std::make_shared<BitCodeAbbrev>();
4185 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
4186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
4187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
4189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
4190
4192 CONSTANTS_CE_CAST_Abbrev)
4193 llvm_unreachable("Unexpected abbrev ordering!");
4194 }
4195 { // NULL abbrev for CONSTANTS_BLOCK.
4196 auto Abbv = std::make_shared<BitCodeAbbrev>();
4197 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
4199 CONSTANTS_NULL_Abbrev)
4200 llvm_unreachable("Unexpected abbrev ordering!");
4201 }
4202
4203 // FIXME: This should only use space for first class types!
4204
4205 { // INST_LOAD abbrev for FUNCTION_BLOCK.
4206 auto Abbv = std::make_shared<BitCodeAbbrev>();
4207 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
4208 Abbv->Add(ValAbbrevOp); // Ptr
4209 Abbv->Add(TypeAbbrevOp); // dest ty
4210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
4211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4212 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4213 FUNCTION_INST_LOAD_ABBREV)
4214 llvm_unreachable("Unexpected abbrev ordering!");
4215 }
4216 {
4217 auto Abbv = std::make_shared<BitCodeAbbrev>();
4218 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_STORE));
4219 Abbv->Add(ValAbbrevOp); // op1
4220 Abbv->Add(ValAbbrevOp); // op0
4221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // align
4222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
4223 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4224 FUNCTION_INST_STORE_ABBREV)
4225 llvm_unreachable("Unexpected abbrev ordering!");
4226 }
4227 { // INST_UNOP abbrev for FUNCTION_BLOCK.
4228 auto Abbv = std::make_shared<BitCodeAbbrev>();
4229 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4230 Abbv->Add(ValAbbrevOp); // LHS
4231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4232 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4233 FUNCTION_INST_UNOP_ABBREV)
4234 llvm_unreachable("Unexpected abbrev ordering!");
4235 }
4236 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
4237 auto Abbv = std::make_shared<BitCodeAbbrev>();
4238 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
4239 Abbv->Add(ValAbbrevOp); // LHS
4240 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4242 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4243 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4244 llvm_unreachable("Unexpected abbrev ordering!");
4245 }
4246 { // INST_BINOP abbrev for FUNCTION_BLOCK.
4247 auto Abbv = std::make_shared<BitCodeAbbrev>();
4248 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4249 Abbv->Add(ValAbbrevOp); // LHS
4250 Abbv->Add(ValAbbrevOp); // RHS
4251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4252 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4253 FUNCTION_INST_BINOP_ABBREV)
4254 llvm_unreachable("Unexpected abbrev ordering!");
4255 }
4256 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
4257 auto Abbv = std::make_shared<BitCodeAbbrev>();
4258 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
4259 Abbv->Add(ValAbbrevOp); // LHS
4260 Abbv->Add(ValAbbrevOp); // RHS
4261 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4263 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4264 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4265 llvm_unreachable("Unexpected abbrev ordering!");
4266 }
4267 { // INST_CAST abbrev for FUNCTION_BLOCK.
4268 auto Abbv = std::make_shared<BitCodeAbbrev>();
4269 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4270 Abbv->Add(ValAbbrevOp); // OpVal
4271 Abbv->Add(TypeAbbrevOp); // dest ty
4272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4273 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4274 FUNCTION_INST_CAST_ABBREV)
4275 llvm_unreachable("Unexpected abbrev ordering!");
4276 }
4277 { // INST_CAST_FLAGS abbrev for FUNCTION_BLOCK.
4278 auto Abbv = std::make_shared<BitCodeAbbrev>();
4279 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
4280 Abbv->Add(ValAbbrevOp); // OpVal
4281 Abbv->Add(TypeAbbrevOp); // dest ty
4282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
4283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 9)); // flags
4284 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4285 FUNCTION_INST_CAST_FLAGS_ABBREV)
4286 llvm_unreachable("Unexpected abbrev ordering!");
4287 }
4288
4289 { // INST_RET abbrev for FUNCTION_BLOCK.
4290 auto Abbv = std::make_shared<BitCodeAbbrev>();
4291 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4292 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4293 FUNCTION_INST_RET_VOID_ABBREV)
4294 llvm_unreachable("Unexpected abbrev ordering!");
4295 }
4296 { // INST_RET abbrev for FUNCTION_BLOCK.
4297 auto Abbv = std::make_shared<BitCodeAbbrev>();
4298 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
4299 Abbv->Add(ValAbbrevOp);
4300 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4301 FUNCTION_INST_RET_VAL_ABBREV)
4302 llvm_unreachable("Unexpected abbrev ordering!");
4303 }
4304 {
4305 auto Abbv = std::make_shared<BitCodeAbbrev>();
4306 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4307 // TODO: Use different abbrev for absolute value reference (succ0)?
4308 Abbv->Add(ValAbbrevOp); // succ0
4309 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4310 FUNCTION_INST_BR_UNCOND_ABBREV)
4311 llvm_unreachable("Unexpected abbrev ordering!");
4312 }
4313 {
4314 auto Abbv = std::make_shared<BitCodeAbbrev>();
4315 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BR));
4316 // TODO: Use different abbrev for absolute value references (succ0, succ1)?
4317 Abbv->Add(ValAbbrevOp); // succ0
4318 Abbv->Add(ValAbbrevOp); // succ1
4319 Abbv->Add(ValAbbrevOp); // cond
4320 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4321 FUNCTION_INST_BR_COND_ABBREV)
4322 llvm_unreachable("Unexpected abbrev ordering!");
4323 }
4324 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
4325 auto Abbv = std::make_shared<BitCodeAbbrev>();
4326 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
4327 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4328 FUNCTION_INST_UNREACHABLE_ABBREV)
4329 llvm_unreachable("Unexpected abbrev ordering!");
4330 }
4331 {
4332 auto Abbv = std::make_shared<BitCodeAbbrev>();
4333 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
4334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // flags
4335 Abbv->Add(TypeAbbrevOp); // dest ty
4336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4337 Abbv->Add(ValAbbrevOp);
4338 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4339 FUNCTION_INST_GEP_ABBREV)
4340 llvm_unreachable("Unexpected abbrev ordering!");
4341 }
4342 {
4343 auto Abbv = std::make_shared<BitCodeAbbrev>();
4344 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4345 Abbv->Add(ValAbbrevOp); // op0
4346 Abbv->Add(ValAbbrevOp); // op1
4347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4348 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4349 FUNCTION_INST_CMP_ABBREV)
4350 llvm_unreachable("Unexpected abbrev ordering!");
4351 }
4352 {
4353 auto Abbv = std::make_shared<BitCodeAbbrev>();
4354 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CMP2));
4355 Abbv->Add(ValAbbrevOp); // op0
4356 Abbv->Add(ValAbbrevOp); // op1
4357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 6)); // pred
4358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
4359 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4360 FUNCTION_INST_CMP_FLAGS_ABBREV)
4361 llvm_unreachable("Unexpected abbrev ordering!");
4362 }
4363 {
4364 auto Abbv = std::make_shared<BitCodeAbbrev>();
4365 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE));
4366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // dbgloc
4367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // var
4368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 7)); // expr
4369 Abbv->Add(ValAbbrevOp); // val
4370 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4371 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4372 llvm_unreachable("Unexpected abbrev ordering! 1");
4373 }
4374 {
4375 auto Abbv = std::make_shared<BitCodeAbbrev>();
4376 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4377 // NOTE: No IsDistinct field for FUNC_CODE_DEBUG_LOC.
4378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4385 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4386 FUNCTION_DEBUG_LOC_ABBREV)
4387 llvm_unreachable("Unexpected abbrev ordering!");
4388 }
4389 { // DEBUG_LOC abbrev for FUNCTION_BLOCK, irlayers variant.
4390 // Separate abbrev so a location without layers does not spend a VBR chunk
4391 // encoding a zero; writeInstruction picks between the two per record.
4392 auto Abbv = std::make_shared<BitCodeAbbrev>();
4393 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_DEBUG_LOC));
4394 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
4399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Atom group.
4400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Atom rank.
4401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // irlayers.
4402 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
4403 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4404 llvm_unreachable("Unexpected abbrev ordering!");
4405 }
4406 Stream.ExitBlock();
4407}
4408
4409/// Write the module path strings, currently only used when generating
4410/// a combined index file.
4411void IndexBitcodeWriter::writeModStrings() {
4413
4414 // TODO: See which abbrev sizes we actually need to emit
4415
4416 // 8-bit fixed-width MST_ENTRY strings.
4417 auto Abbv = std::make_shared<BitCodeAbbrev>();
4418 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4420 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4421 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
4422 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
4423
4424 // 7-bit fixed width MST_ENTRY strings.
4425 Abbv = std::make_shared<BitCodeAbbrev>();
4426 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4427 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4428 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4429 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
4430 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
4431
4432 // 6-bit char6 MST_ENTRY strings.
4433 Abbv = std::make_shared<BitCodeAbbrev>();
4434 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
4435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4438 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
4439
4440 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
4441 Abbv = std::make_shared<BitCodeAbbrev>();
4442 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
4443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4448 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
4449
4451 forEachModule([&](const StringMapEntry<ModuleHash> &MPSE) {
4452 StringRef Key = MPSE.getKey();
4453 const auto &Hash = MPSE.getValue();
4455 unsigned AbbrevToUse = Abbrev8Bit;
4456 if (Bits == SE_Char6)
4457 AbbrevToUse = Abbrev6Bit;
4458 else if (Bits == SE_Fixed7)
4459 AbbrevToUse = Abbrev7Bit;
4460
4461 auto ModuleId = ModuleIdMap.size();
4462 ModuleIdMap[Key] = ModuleId;
4463 Vals.push_back(ModuleId);
4464 // Use bytes_begin/end() for unsigned char iteration.
4465 Vals.append(Key.bytes_begin(), Key.bytes_end());
4466
4467 // Emit the finished record.
4468 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
4469
4470 // Emit an optional hash for the module now
4471 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
4472 Vals.assign(Hash.begin(), Hash.end());
4473 // Emit the hash record.
4474 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
4475 }
4476
4477 Vals.clear();
4478 });
4479 Stream.ExitBlock();
4480}
4481
4482/// Write the function type metadata related records that need to appear before
4483/// a function summary entry (whether per-module or combined).
4484template <typename Fn>
4486 FunctionSummary *FS,
4487 Fn GetValueID) {
4488 if (!FS->type_tests().empty())
4489 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
4490
4492
4493 auto WriteVFuncIdVec = [&](uint64_t Ty,
4495 if (VFs.empty())
4496 return;
4497 Record.clear();
4498 for (auto &VF : VFs) {
4499 Record.push_back(VF.GUID);
4500 Record.push_back(VF.Offset);
4501 }
4502 Stream.EmitRecord(Ty, Record);
4503 };
4504
4505 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
4506 FS->type_test_assume_vcalls());
4507 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
4508 FS->type_checked_load_vcalls());
4509
4510 auto WriteConstVCallVec = [&](uint64_t Ty,
4512 for (auto &VC : VCs) {
4513 Record.clear();
4514 Record.push_back(VC.VFunc.GUID);
4515 Record.push_back(VC.VFunc.Offset);
4516 llvm::append_range(Record, VC.Args);
4517 Stream.EmitRecord(Ty, Record);
4518 }
4519 };
4520
4521 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
4522 FS->type_test_assume_const_vcalls());
4523 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
4524 FS->type_checked_load_const_vcalls());
4525
4526 auto WriteRange = [&](ConstantRange Range) {
4528 assert(Range.getLower().getNumWords() == 1);
4529 assert(Range.getUpper().getNumWords() == 1);
4530 emitSignedInt64(Record, *Range.getLower().getRawData());
4531 emitSignedInt64(Record, *Range.getUpper().getRawData());
4532 };
4533
4534 if (!FS->paramAccesses().empty()) {
4535 Record.clear();
4536 for (auto &Arg : FS->paramAccesses()) {
4537 size_t UndoSize = Record.size();
4538 Record.push_back(Arg.ParamNo);
4539 WriteRange(Arg.Use);
4540 Record.push_back(Arg.Calls.size());
4541 for (auto &Call : Arg.Calls) {
4542 Record.push_back(Call.ParamNo);
4543 std::optional<unsigned> ValueID = GetValueID(Call.Callee);
4544 if (!ValueID) {
4545 // If ValueID is unknown we can't drop just this call, we must drop
4546 // entire parameter.
4547 Record.resize(UndoSize);
4548 break;
4549 }
4550 Record.push_back(*ValueID);
4551 WriteRange(Call.Offsets);
4552 }
4553 }
4554 if (!Record.empty())
4556 }
4557}
4558
4559/// Collect type IDs from type tests used by function.
4560static void
4562 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4563 if (!FS->type_tests().empty())
4564 for (auto &TT : FS->type_tests())
4565 ReferencedTypeIds.insert(TT);
4566
4567 auto GetReferencedTypesFromVFuncIdVec =
4569 for (auto &VF : VFs)
4570 ReferencedTypeIds.insert(VF.GUID);
4571 };
4572
4573 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4574 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4575
4576 auto GetReferencedTypesFromConstVCallVec =
4578 for (auto &VC : VCs)
4579 ReferencedTypeIds.insert(VC.VFunc.GUID);
4580 };
4581
4582 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4583 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4584}
4585
4587 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
4589 NameVals.push_back(args.size());
4590 llvm::append_range(NameVals, args);
4591
4592 NameVals.push_back(ByArg.TheKind);
4593 NameVals.push_back(ByArg.Info);
4594 NameVals.push_back(ByArg.Byte);
4595 NameVals.push_back(ByArg.Bit);
4596}
4597
4599 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4600 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
4601 NameVals.push_back(Id);
4602
4603 NameVals.push_back(Wpd.TheKind);
4604 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
4605 NameVals.push_back(Wpd.SingleImplName.size());
4606
4607 NameVals.push_back(Wpd.ResByArg.size());
4608 for (auto &A : Wpd.ResByArg)
4609 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
4610}
4611
4613 StringTableBuilder &StrtabBuilder,
4614 StringRef Id,
4615 const TypeIdSummary &Summary) {
4616 NameVals.push_back(StrtabBuilder.add(Id));
4617 NameVals.push_back(Id.size());
4618
4619 NameVals.push_back(Summary.TTRes.TheKind);
4620 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
4621 NameVals.push_back(Summary.TTRes.AlignLog2);
4622 NameVals.push_back(Summary.TTRes.SizeM1);
4623 NameVals.push_back(Summary.TTRes.BitMask);
4624 NameVals.push_back(Summary.TTRes.InlineBits);
4625
4626 for (auto &W : Summary.WPDRes)
4627 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
4628 W.second);
4629}
4630
4632 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
4633 StringRef Id, const TypeIdCompatibleVtableInfo &Summary,
4635 NameVals.push_back(StrtabBuilder.add(Id));
4636 NameVals.push_back(Id.size());
4637
4638 for (auto &P : Summary) {
4639 NameVals.push_back(P.AddressPointOffset);
4640 NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
4641 }
4642}
4643
4644// Adds the allocation contexts to the CallStacks map. We simply use the
4645// size at the time the context was added as the CallStackId. This works because
4646// when we look up the call stacks later on we process the function summaries
4647// and their allocation records in the same exact order.
4649 FunctionSummary *FS, std::function<LinearFrameId(unsigned)> GetStackIndex,
4651 // The interfaces in ProfileData/MemProf.h use a type alias for a stack frame
4652 // id offset into the index of the full stack frames. The ModuleSummaryIndex
4653 // currently uses unsigned. Make sure these stay in sync.
4654 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4655 for (auto &AI : FS->allocs()) {
4656 for (auto &MIB : AI.MIBs) {
4657 SmallVector<unsigned> StackIdIndices;
4658 StackIdIndices.reserve(MIB.StackIdIndices.size());
4659 for (auto Id : MIB.StackIdIndices)
4660 StackIdIndices.push_back(GetStackIndex(Id));
4661 // The CallStackId is the size at the time this context was inserted.
4662 CallStacks.insert({CallStacks.size(), StackIdIndices});
4663 }
4664 }
4665}
4666
4667// Build the radix tree from the accumulated CallStacks, write out the resulting
4668// linearized radix tree array, and return the map of call stack positions into
4669// this array for use when writing the allocation records. The returned map is
4670// indexed by a CallStackId which in this case is implicitly determined by the
4671// order of function summaries and their allocation infos being written.
4674 BitstreamWriter &Stream, unsigned RadixAbbrev) {
4675 assert(!CallStacks.empty());
4676 DenseMap<unsigned, FrameStat> FrameHistogram =
4679 // We don't need a MemProfFrameIndexes map as we have already converted the
4680 // full stack id hash to a linear offset into the StackIds array.
4681 Builder.build(std::move(CallStacks), /*MemProfFrameIndexes=*/nullptr,
4682 FrameHistogram);
4683 Stream.EmitRecord(bitc::FS_CONTEXT_RADIX_TREE_ARRAY, Builder.getRadixArray(),
4684 RadixAbbrev);
4685 return Builder.takeCallStackPos();
4686}
4687
4689 BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev,
4690 unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule,
4691 std::function<unsigned(const ValueInfo &VI)> GetValueID,
4692 std::function<unsigned(unsigned)> GetStackIndex,
4693 bool WriteContextSizeInfoIndex,
4695 CallStackId &CallStackCount) {
4697
4698 for (auto &CI : FS->callsites()) {
4699 Record.clear();
4700 // Per module callsite clones should always have a single entry of
4701 // value 0.
4702 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4703 Record.push_back(GetValueID(CI.Callee));
4704 if (!PerModule) {
4705 Record.push_back(CI.StackIdIndices.size());
4706 Record.push_back(CI.Clones.size());
4707 }
4708 for (auto Id : CI.StackIdIndices)
4709 Record.push_back(GetStackIndex(Id));
4710 if (!PerModule)
4711 llvm::append_range(Record, CI.Clones);
4714 Record, CallsiteAbbrev);
4715 }
4716
4717 for (auto &AI : FS->allocs()) {
4718 Record.clear();
4719 // Per module alloc versions should always have a single entry of
4720 // value 0.
4721 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4722 Record.push_back(AI.MIBs.size());
4723 if (!PerModule)
4724 Record.push_back(AI.Versions.size());
4725 for (auto &MIB : AI.MIBs) {
4726 Record.push_back((uint8_t)MIB.AllocType);
4727 // The per-module summary always needs to include the alloc context, as we
4728 // use it during the thin link. For the combined index it is optional (see
4729 // comments where CombinedIndexMemProfContext is defined).
4730 if (PerModule || CombinedIndexMemProfContext) {
4731 // Record the index into the radix tree array for this context.
4732 assert(CallStackCount <= CallStackPos.size());
4733 Record.push_back(CallStackPos[CallStackCount++]);
4734 }
4735 }
4736 if (!PerModule)
4737 llvm::append_range(Record, AI.Versions);
4738 assert(AI.ContextSizeInfos.empty() ||
4739 AI.ContextSizeInfos.size() == AI.MIBs.size());
4740 // Optionally emit the context size information if it exists.
4741 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4742 // The abbreviation id for the context ids record should have been created
4743 // if we are emitting the per-module index, which is where we write this
4744 // info.
4745 assert(ContextIdAbbvId);
4746 SmallVector<uint32_t> ContextIds;
4747 // At least one context id per ContextSizeInfos entry (MIB), broken into 2
4748 // halves.
4749 ContextIds.reserve(AI.ContextSizeInfos.size() * 2);
4750 for (auto &Infos : AI.ContextSizeInfos) {
4751 Record.push_back(Infos.size());
4752 for (auto [FullStackId, TotalSize] : Infos) {
4753 // The context ids are emitted separately as a fixed width array,
4754 // which is more efficient than a VBR given that these hashes are
4755 // typically close to 64-bits. The max fixed width entry is 32 bits so
4756 // it is split into 2.
4757 ContextIds.push_back(static_cast<uint32_t>(FullStackId >> 32));
4758 ContextIds.push_back(static_cast<uint32_t>(FullStackId));
4759 Record.push_back(TotalSize);
4760 }
4761 }
4762 // The context ids are expected by the reader to immediately precede the
4763 // associated alloc info record.
4764 Stream.EmitRecord(bitc::FS_ALLOC_CONTEXT_IDS, ContextIds,
4765 ContextIdAbbvId);
4766 }
4767 Stream.EmitRecord(PerModule
4772 Record, AllocAbbrev);
4773 }
4774}
4775
4776// Helper to emit a single function summary record.
4777void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4778 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4779 unsigned ValueID, unsigned FSCallsProfileAbbrev, unsigned CallsiteAbbrev,
4780 unsigned AllocAbbrev, unsigned ContextIdAbbvId, const Function &F,
4781 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4782 CallStackId &CallStackCount) {
4783 NameVals.push_back(ValueID);
4784
4785 FunctionSummary *FS = cast<FunctionSummary>(Summary);
4786
4788 Stream, FS, [&](const ValueInfo &VI) -> std::optional<unsigned> {
4789 return {VE.getValueID(VI.getValue())};
4790 });
4791
4792 auto SpecialRefCnts = FS->specialRefCounts();
4793 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4794 NameVals.push_back(FS->instCount());
4795 NameVals.push_back(getEncodedFFlags(FS->fflags()));
4796 NameVals.push_back(FS->refs().size());
4797 NameVals.push_back(SpecialRefCnts.first); // rorefcnt
4798 NameVals.push_back(SpecialRefCnts.second); // worefcnt
4799
4800 for (auto &RI : FS->refs())
4801 NameVals.push_back(getValueId(RI));
4802
4803 for (auto &ECI : FS->calls()) {
4804 NameVals.push_back(getValueId(ECI.first));
4805 NameVals.push_back(getEncodedHotnessCallEdgeInfo(ECI.second));
4806 }
4807
4808 // Emit the finished record.
4809 Stream.EmitRecord(bitc::FS_PERMODULE_PROFILE, NameVals, FSCallsProfileAbbrev);
4810 NameVals.clear();
4811
4813 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4814 /*PerModule*/ true,
4815 /*GetValueId*/ [&](const ValueInfo &VI) { return getValueId(VI); },
4816 /*GetStackIndex*/ [&](unsigned I) { return I; },
4817 /*WriteContextSizeInfoIndex*/ true, CallStackPos, CallStackCount);
4818}
4819
4820// Collect the global value references in the given variable's initializer,
4821// and emit them in a summary record.
4822void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4823 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4824 unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
4825 // Be a little lenient here, to accomodate older files without GUIDs
4826 // already computed and assigned as metadata.
4827 GlobalValue::GUID GUID = V.getGUIDOrFallback();
4828
4829 auto VI = Index->getValueInfo(GUID);
4830 if (!VI || VI.getSummaryList().empty()) {
4831 // Only declarations should not have a summary (a declaration might however
4832 // have a summary if the def was in module level asm).
4833 assert(V.isDeclaration());
4834 return;
4835 }
4836 auto *Summary = VI.getSummaryList()[0].get();
4837 NameVals.push_back(VE.getValueID(&V));
4838 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
4839 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4840 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4841
4842 auto VTableFuncs = VS->vTableFuncs();
4843 if (!VTableFuncs.empty())
4844 NameVals.push_back(VS->refs().size());
4845
4846 unsigned SizeBeforeRefs = NameVals.size();
4847 for (auto &RI : VS->refs())
4848 NameVals.push_back(VE.getValueID(RI.getValue()));
4849 // Sort the refs for determinism output, the vector returned by FS->refs() has
4850 // been initialized from a DenseSet.
4851 llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
4852
4853 if (VTableFuncs.empty())
4855 FSModRefsAbbrev);
4856 else {
4857 // VTableFuncs pairs should already be sorted by offset.
4858 for (auto &P : VTableFuncs) {
4859 NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
4860 NameVals.push_back(P.VTableOffset);
4861 }
4862
4864 FSModVTableRefsAbbrev);
4865 }
4866 NameVals.clear();
4867}
4868
4869/// Emit the per-module summary section alongside the rest of
4870/// the module's bitcode.
4871void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4872 // By default we compile with ThinLTO if the module has a summary, but the
4873 // client can request full LTO with a module flag.
4874 bool IsThinLTO = true;
4875 if (auto *MD =
4876 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
4877 IsThinLTO = MD->getZExtValue();
4880 4);
4881
4882 Stream.EmitRecord(
4884 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4885
4886 // Write the index flags.
4887 uint64_t Flags = 0;
4888 // Bits 1-3 are set only in the combined index, skip them.
4889 if (Index->enableSplitLTOUnit())
4890 Flags |= 0x8;
4891 if (Index->hasUnifiedLTO())
4892 Flags |= 0x200;
4893
4894 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
4895
4896 if (Index->begin() == Index->end()) {
4897 Stream.ExitBlock();
4898 return;
4899 }
4900
4901 auto Abbv = std::make_shared<BitCodeAbbrev>();
4902 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
4903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4904 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
4905 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4906 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4907 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4908
4909 for (const auto &GVI : valueIds()) {
4911 ArrayRef<uint32_t>{GVI.second,
4912 static_cast<uint32_t>(GVI.first >> 32),
4913 static_cast<uint32_t>(GVI.first)},
4914 ValueGuidAbbrev);
4915 }
4916
4917 if (!Index->stackIds().empty()) {
4918 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4919 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
4920 // numids x stackid
4921 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4922 // The stack ids are hashes that are close to 64 bits in size, so emitting
4923 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
4924 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4925 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
4926 SmallVector<uint32_t> Vals;
4927 Vals.reserve(Index->stackIds().size() * 2);
4928 for (auto Id : Index->stackIds()) {
4929 Vals.push_back(static_cast<uint32_t>(Id >> 32));
4930 Vals.push_back(static_cast<uint32_t>(Id));
4931 }
4932 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
4933 }
4934
4935 unsigned ContextIdAbbvId = 0;
4937 // n x context id
4938 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4939 ContextIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_ALLOC_CONTEXT_IDS));
4940 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4941 // The context ids are hashes that are close to 64 bits in size, so emitting
4942 // as a pair of 32-bit fixed-width values is more efficient than a VBR if we
4943 // are emitting them for all MIBs. Otherwise we use VBR to better compress 0
4944 // values that are expected to more frequently occur in an alloc's memprof
4945 // summary.
4947 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
4948 else
4949 ContextIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4950 ContextIdAbbvId = Stream.EmitAbbrev(std::move(ContextIdAbbv));
4951 }
4952
4953 // Abbrev for FS_PERMODULE_PROFILE.
4954 Abbv = std::make_shared<BitCodeAbbrev>();
4955 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
4956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // flags
4958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4963 // numrefs x valueid, n x (valueid, hotness+tailcall+indirectcall flags)
4964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4966 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4967
4968 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4969 Abbv = std::make_shared<BitCodeAbbrev>();
4970 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
4971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4975 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4976
4977 // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4978 Abbv = std::make_shared<BitCodeAbbrev>();
4979 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
4980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4981 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4983 // numrefs x valueid, n x (valueid , offset)
4984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4986 unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4987
4988 // Abbrev for FS_ALIAS.
4989 Abbv = std::make_shared<BitCodeAbbrev>();
4990 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4992 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4993 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4994 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4995
4996 // Abbrev for FS_TYPE_ID_METADATA
4997 Abbv = std::make_shared<BitCodeAbbrev>();
4998 Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
5000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
5001 // n x (valueid , offset)
5002 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5003 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5004 unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5005
5006 Abbv = std::make_shared<BitCodeAbbrev>();
5007 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_CALLSITE_INFO));
5008 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5009 // n x stackidindex
5010 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5012 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5013
5014 Abbv = std::make_shared<BitCodeAbbrev>();
5015 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_ALLOC_INFO));
5016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5017 // n x (alloc type, context radix tree index)
5018 // optional: nummib x (numcontext x total size)
5019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5021 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5022
5023 Abbv = std::make_shared<BitCodeAbbrev>();
5024 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5025 // n x entry
5026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5028 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5029
5030 // First walk through all the functions and collect the allocation contexts in
5031 // their associated summaries, for use in constructing a radix tree of
5032 // contexts. Note that we need to do this in the same order as the functions
5033 // are processed further below since the call stack positions in the resulting
5034 // radix tree array are identified based on this order.
5035 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5036 for (const Function &F : M) {
5037 // Summary emission does not support anonymous functions, they have to be
5038 // renamed using the anonymous function renaming pass.
5039 if (!F.hasName())
5040 report_fatal_error("Unexpected anonymous function when writing summary");
5041
5042 // Be a little lenient here, to accomodate older files without GUIDs
5043 // already computed and assigned as metadata.
5044 GlobalValue::GUID GUID = F.getGUIDOrFallback();
5045
5046 ValueInfo VI = Index->getValueInfo(GUID);
5047 if (!VI || VI.getSummaryList().empty()) {
5048 // Only declarations should not have a summary (a declaration might
5049 // however have a summary if the def was in module level asm).
5050 if (!F.isDeclaration())
5051 reportFatalUsageError("expected function definition " + F.getName() +
5052 " to have an associated value info.");
5053 continue;
5054 }
5055 auto *Summary = VI.getSummaryList()[0].get();
5056 FunctionSummary *FS = cast<FunctionSummary>(Summary);
5058 FS, /*GetStackIndex*/ [](unsigned I) { return I; }, CallStacks);
5059 }
5060 // Finalize the radix tree, write it out, and get the map of positions in the
5061 // linearized tree array.
5062 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5063 if (!CallStacks.empty()) {
5064 CallStackPos =
5065 writeMemoryProfileRadixTree(std::move(CallStacks), Stream, RadixAbbrev);
5066 }
5067
5068 // Keep track of the current index into the CallStackPos map.
5069 CallStackId CallStackCount = 0;
5070
5071 SmallVector<uint64_t, 64> NameVals;
5072 // Iterate over the list of functions instead of the Index to
5073 // ensure the ordering is stable.
5074 for (const Function &F : M) {
5075 // Summary emission does not support anonymous functions, they have to
5076 // renamed using the anonymous function renaming pass.
5077 if (!F.hasName())
5078 report_fatal_error("Unexpected anonymous function when writing summary");
5079
5080 GlobalValue::GUID GUID = F.getGUIDOrFallback();
5081
5082 ValueInfo VI = Index->getValueInfo(GUID);
5083 if (!VI || VI.getSummaryList().empty()) {
5084 // Only declarations should not have a summary (a declaration might
5085 // however have a summary if the def was in module level asm).
5086 assert(F.isDeclaration());
5087 continue;
5088 }
5089 auto *Summary = VI.getSummaryList()[0].get();
5090 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
5091 FSCallsProfileAbbrev, CallsiteAbbrev,
5092 AllocAbbrev, ContextIdAbbvId, F,
5093 CallStackPos, CallStackCount);
5094 }
5095
5096 // Capture references from GlobalVariable initializers, which are outside
5097 // of a function scope.
5098 for (const GlobalVariable &G : M.globals())
5099 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
5100 FSModVTableRefsAbbrev);
5101
5102 for (const GlobalAlias &A : M.aliases()) {
5103 auto *Aliasee = A.getAliaseeObject();
5104 // Skip ifunc and nameless functions which don't have an entry in the
5105 // summary.
5106 if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
5107 continue;
5108 auto AliasId = VE.getValueID(&A);
5109 auto AliaseeId = VE.getValueID(Aliasee);
5110 NameVals.push_back(AliasId);
5111 auto *Summary = Index->getGlobalValueSummary(A);
5112 AliasSummary *AS = cast<AliasSummary>(Summary);
5113 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
5114 NameVals.push_back(AliaseeId);
5115 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
5116 NameVals.clear();
5117 }
5118
5119 for (auto &S : Index->typeIdCompatibleVtableMap()) {
5120 writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
5121 S.second, VE);
5122 Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
5123 TypeIdCompatibleVtableAbbrev);
5124 NameVals.clear();
5125 }
5126
5127 if (Index->getBlockCount())
5129 ArrayRef<uint64_t>{Index->getBlockCount()});
5130
5131 Stream.ExitBlock();
5132}
5133
5134void ModuleBitcodeWriterBase::writeGUIDList() {
5136 for (const GlobalValue &GV : M.global_values()) {
5137 auto MaybeGUID = GV.getGUIDIfAssigned();
5138 if (!MaybeGUID || *MaybeGUID == 0)
5139 continue;
5140 const auto ValueID = VE.getValueID(&GV);
5141 if (ValueID >= GUIDs.size())
5142 GUIDs.resize(ValueID + 1);
5143 GUIDs[ValueID] = *MaybeGUID;
5144 }
5145
5146 auto Abbv = std::make_shared<BitCodeAbbrev>();
5147 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GUIDLIST));
5148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5150 unsigned GUIDListAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5151
5152 SmallVector<uint32_t> RecordVals;
5153 RecordVals.reserve(GUIDs.size() * 2);
5154 for (auto GUID : GUIDs) {
5155 RecordVals.push_back(static_cast<uint32_t>(GUID >> 32));
5156 RecordVals.push_back(static_cast<uint32_t>(GUID));
5157 }
5158
5159 Stream.EmitRecord(bitc::MODULE_CODE_GUIDLIST, RecordVals, GUIDListAbbrev);
5160}
5161
5162/// Emit the combined summary section into the combined index file.
5163void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5165 Stream.EmitRecord(
5167 ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
5168
5169 // Write the index flags.
5170 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
5171
5172 auto Abbv = std::make_shared<BitCodeAbbrev>();
5173 Abbv->Add(BitCodeAbbrevOp(bitc::FS_VALUE_GUID));
5174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
5175 // GUIDS often use up most of 64-bits, so encode as two Fixed 32.
5176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5178 unsigned ValueGuidAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5179
5180 for (const auto &GVI : valueIds()) {
5182 ArrayRef<uint32_t>{GVI.second,
5183 static_cast<uint32_t>(GVI.first >> 32),
5184 static_cast<uint32_t>(GVI.first)},
5185 ValueGuidAbbrev);
5186 }
5187
5188 // Write the stack ids used by this index, which will be a subset of those in
5189 // the full index in the case of distributed indexes.
5190 if (!StackIds.empty()) {
5191 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5192 StackIdAbbv->Add(BitCodeAbbrevOp(bitc::FS_STACK_IDS));
5193 // numids x stackid
5194 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5195 // The stack ids are hashes that are close to 64 bits in size, so emitting
5196 // as a pair of 32-bit fixed-width values is more efficient than a VBR.
5197 StackIdAbbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
5198 unsigned StackIdAbbvId = Stream.EmitAbbrev(std::move(StackIdAbbv));
5199 SmallVector<uint32_t> Vals;
5200 Vals.reserve(StackIds.size() * 2);
5201 for (auto Id : StackIds) {
5202 Vals.push_back(static_cast<uint32_t>(Id >> 32));
5203 Vals.push_back(static_cast<uint32_t>(Id));
5204 }
5205 Stream.EmitRecord(bitc::FS_STACK_IDS, Vals, StackIdAbbvId);
5206 }
5207
5208 // Abbrev for FS_COMBINED_PROFILE.
5209 Abbv = std::make_shared<BitCodeAbbrev>();
5210 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
5211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
5215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
5216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
5217 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
5218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
5219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
5220 // numrefs x valueid, n x (valueid, hotness+tailcall+indirectcall flags)
5221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5223 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5224
5225 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
5226 Abbv = std::make_shared<BitCodeAbbrev>();
5227 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
5228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
5232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5233 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5234
5235 // Abbrev for FS_COMBINED_ALIAS.
5236 Abbv = std::make_shared<BitCodeAbbrev>();
5237 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
5238 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5239 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
5240 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
5241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5242 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5243
5244 Abbv = std::make_shared<BitCodeAbbrev>();
5245 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_CALLSITE_INFO));
5246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
5247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numstackindices
5248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5249 // numstackindices x stackidindex, numver x version
5250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5252 unsigned CallsiteAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5253
5254 Abbv = std::make_shared<BitCodeAbbrev>();
5255 Abbv->Add(BitCodeAbbrevOp(CombinedIndexMemProfContext
5258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // nummib
5259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numver
5260 // nummib x (alloc type, context radix tree index),
5261 // numver x version
5262 // optional: nummib x total size
5263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5265 unsigned AllocAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5266
5267 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) -> bool {
5268 if (DecSummaries == nullptr)
5269 return false;
5270 return DecSummaries->count(GVS);
5271 };
5272
5273 // The aliases are emitted as a post-pass, and will point to the value
5274 // id of the aliasee. Save them in a vector for post-processing.
5276
5277 // Save the value id for each summary for alias emission.
5278 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5279
5280 SmallVector<uint64_t, 64> NameVals;
5281
5282 // Set that will be populated during call to writeFunctionTypeMetadataRecords
5283 // with the type ids referenced by this index file.
5284 std::set<GlobalValue::GUID> ReferencedTypeIds;
5285
5286 // For local linkage, we also emit the original name separately
5287 // immediately after the record.
5288 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5289 // We don't need to emit the original name if we are writing the index for
5290 // distributed backends (in which case ModuleToSummariesForIndex is
5291 // non-null). The original name is only needed during the thin link, since
5292 // for SamplePGO the indirect call targets for local functions have
5293 // have the original name annotated in profile.
5294 // Continue to emit it when writing out the entire combined index, which is
5295 // used in testing the thin link via llvm-lto.
5296 if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
5297 return;
5298 NameVals.push_back(S.getOriginalName());
5300 NameVals.clear();
5301 };
5302
5303 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5305 Abbv = std::make_shared<BitCodeAbbrev>();
5306 Abbv->Add(BitCodeAbbrevOp(bitc::FS_CONTEXT_RADIX_TREE_ARRAY));
5307 // n x entry
5308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
5309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
5310 unsigned RadixAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5311
5312 // First walk through all the functions and collect the allocation contexts
5313 // in their associated summaries, for use in constructing a radix tree of
5314 // contexts. Note that we need to do this in the same order as the functions
5315 // are processed further below since the call stack positions in the
5316 // resulting radix tree array are identified based on this order.
5317 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5318 forEachSummary([&](GVInfo I, bool IsAliasee) {
5319 // Don't collect this when invoked for an aliasee, as it is not needed for
5320 // the alias summary. If the aliasee is to be imported, we will invoke
5321 // this separately with IsAliasee=false.
5322 if (IsAliasee)
5323 return;
5324 GlobalValueSummary *S = I.second;
5325 assert(S);
5326 auto *FS = dyn_cast<FunctionSummary>(S);
5327 if (!FS)
5328 return;
5330 FS,
5331 /*GetStackIndex*/
5332 [&](unsigned I) {
5333 // Get the corresponding index into the list of StackIds actually
5334 // being written for this combined index (which may be a subset in
5335 // the case of distributed indexes).
5336 assert(StackIdIndicesToIndex.contains(I));
5337 return StackIdIndicesToIndex[I];
5338 },
5339 CallStacks);
5340 });
5341 // Finalize the radix tree, write it out, and get the map of positions in
5342 // the linearized tree array.
5343 if (!CallStacks.empty()) {
5344 CallStackPos = writeMemoryProfileRadixTree(std::move(CallStacks), Stream,
5345 RadixAbbrev);
5346 }
5347 }
5348
5349 // Keep track of the current index into the CallStackPos map. Not used if
5350 // CombinedIndexMemProfContext is false.
5351 CallStackId CallStackCount = 0;
5352
5353 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5354 forEachSummary([&](GVInfo I, bool IsAliasee) {
5355 GlobalValueSummary *S = I.second;
5356 assert(S);
5357 DefOrUseGUIDs.insert(I.first);
5358 for (const ValueInfo &VI : S->refs())
5359 DefOrUseGUIDs.insert(VI.getGUID());
5360
5361 auto ValueId = getValueId(I.first);
5362 assert(ValueId);
5363 SummaryToValueIdMap[S] = *ValueId;
5364
5365 // If this is invoked for an aliasee, we want to record the above
5366 // mapping, but then not emit a summary entry (if the aliasee is
5367 // to be imported, we will invoke this separately with IsAliasee=false).
5368 if (IsAliasee)
5369 return;
5370
5371 if (auto *AS = dyn_cast<AliasSummary>(S)) {
5372 // Will process aliases as a post-pass because the reader wants all
5373 // global to be loaded first.
5374 Aliases.push_back(AS);
5375 return;
5376 }
5377
5378 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
5379 NameVals.push_back(*ValueId);
5380 assert(ModuleIdMap.count(VS->modulePath()));
5381 NameVals.push_back(ModuleIdMap[VS->modulePath()]);
5382 NameVals.push_back(
5383 getEncodedGVSummaryFlags(VS->flags(), shouldImportValueAsDecl(VS)));
5384 NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
5385 for (auto &RI : VS->refs()) {
5386 auto RefValueId = getValueId(RI.getGUID());
5387 if (!RefValueId)
5388 continue;
5389 NameVals.push_back(*RefValueId);
5390 }
5391
5392 // Emit the finished record.
5394 FSModRefsAbbrev);
5395 NameVals.clear();
5396 MaybeEmitOriginalName(*S);
5397 return;
5398 }
5399
5400 auto GetValueId = [&](const ValueInfo &VI) -> std::optional<unsigned> {
5401 if (!VI)
5402 return std::nullopt;
5403 return getValueId(VI.getGUID());
5404 };
5405
5406 auto *FS = cast<FunctionSummary>(S);
5407 writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
5408 getReferencedTypeIds(FS, ReferencedTypeIds);
5409
5410 NameVals.push_back(*ValueId);
5411 assert(ModuleIdMap.count(FS->modulePath()));
5412 NameVals.push_back(ModuleIdMap[FS->modulePath()]);
5413 NameVals.push_back(
5414 getEncodedGVSummaryFlags(FS->flags(), shouldImportValueAsDecl(FS)));
5415 NameVals.push_back(FS->instCount());
5416 NameVals.push_back(getEncodedFFlags(FS->fflags()));
5417 // TODO: Stop writing entry count and bump bitcode version.
5418 NameVals.push_back(0 /* EntryCount */);
5419
5420 // Fill in below
5421 NameVals.push_back(0); // numrefs
5422 NameVals.push_back(0); // rorefcnt
5423 NameVals.push_back(0); // worefcnt
5424
5425 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5426 for (auto &RI : FS->refs()) {
5427 auto RefValueId = getValueId(RI.getGUID());
5428 if (!RefValueId)
5429 continue;
5430 NameVals.push_back(*RefValueId);
5431 if (RI.isReadOnly())
5432 RORefCnt++;
5433 else if (RI.isWriteOnly())
5434 WORefCnt++;
5435 Count++;
5436 }
5437 NameVals[6] = Count;
5438 NameVals[7] = RORefCnt;
5439 NameVals[8] = WORefCnt;
5440
5441 for (auto &EI : FS->calls()) {
5442 // If this GUID doesn't have a value id, it doesn't have a function
5443 // summary and we don't need to record any calls to it.
5444 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5445 if (!CallValueId)
5446 continue;
5447 NameVals.push_back(*CallValueId);
5448 NameVals.push_back(getEncodedHotnessCallEdgeInfo(EI.second));
5449 }
5450
5451 // Emit the finished record.
5452 Stream.EmitRecord(bitc::FS_COMBINED_PROFILE, NameVals,
5453 FSCallsProfileAbbrev);
5454 NameVals.clear();
5455
5457 Stream, FS, CallsiteAbbrev, AllocAbbrev, /*ContextIdAbbvId*/ 0,
5458 /*PerModule*/ false,
5459 /*GetValueId*/
5460 [&](const ValueInfo &VI) -> unsigned {
5461 std::optional<unsigned> ValueID = GetValueId(VI);
5462 // This can happen in shared index files for distributed ThinLTO if
5463 // the callee function summary is not included. Record 0 which we
5464 // will have to deal with conservatively when doing any kind of
5465 // validation in the ThinLTO backends.
5466 if (!ValueID)
5467 return 0;
5468 return *ValueID;
5469 },
5470 /*GetStackIndex*/
5471 [&](unsigned I) {
5472 // Get the corresponding index into the list of StackIds actually
5473 // being written for this combined index (which may be a subset in
5474 // the case of distributed indexes).
5475 assert(StackIdIndicesToIndex.contains(I));
5476 return StackIdIndicesToIndex[I];
5477 },
5478 /*WriteContextSizeInfoIndex*/ false, CallStackPos, CallStackCount);
5479
5480 MaybeEmitOriginalName(*S);
5481 });
5482
5483 for (auto *AS : Aliases) {
5484 auto AliasValueId = SummaryToValueIdMap[AS];
5485 assert(AliasValueId);
5486 NameVals.push_back(AliasValueId);
5487 assert(ModuleIdMap.count(AS->modulePath()));
5488 NameVals.push_back(ModuleIdMap[AS->modulePath()]);
5489 NameVals.push_back(
5490 getEncodedGVSummaryFlags(AS->flags(), shouldImportValueAsDecl(AS)));
5491 // Set value id to 0 when an alias is imported but the aliasee summary is
5492 // not contained in the index.
5493 auto AliaseeValueId =
5494 AS->hasAliasee() ? SummaryToValueIdMap[&AS->getAliasee()] : 0;
5495 NameVals.push_back(AliaseeValueId);
5496
5497 // Emit the finished record.
5498 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
5499 NameVals.clear();
5500 MaybeEmitOriginalName(*AS);
5501
5502 if (AS->hasAliasee())
5503 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
5504 getReferencedTypeIds(FS, ReferencedTypeIds);
5505 }
5506
5508 auto EmitCfiFunctions = [&](const CfiFunctionIndex &CfiIndex,
5510 if (CfiIndex.empty())
5511 return;
5512 for (GlobalValue::GUID GUID : DefOrUseGUIDs) {
5513 auto Names = CfiIndex.getNamesForGUID(GUID);
5514 for (StringRef Name : Names)
5515 Functions.push_back({Name, GUID});
5516 }
5517 if (Functions.empty())
5518 return;
5519 llvm::sort(Functions);
5520 for (const auto &Record : Functions) {
5521 NameVals.push_back(Record.second);
5522 NameVals.push_back(StrtabBuilder.add(Record.first));
5523 NameVals.push_back(Record.first.size());
5524 }
5525 Stream.EmitRecord(Code, NameVals);
5526 NameVals.clear();
5527 Functions.clear();
5528 };
5529
5530 EmitCfiFunctions(Index.cfiFunctionDefs(), bitc::FS_CFI_FUNCTION_DEFS);
5531 EmitCfiFunctions(Index.cfiFunctionDecls(), bitc::FS_CFI_FUNCTION_DECLS);
5532
5533 // Walk the GUIDs that were referenced, and write the
5534 // corresponding type id records.
5535 for (auto &T : ReferencedTypeIds) {
5536 auto TidIter = Index.typeIds().equal_range(T);
5537 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
5538 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, TypeIdPair.first,
5539 TypeIdPair.second);
5540 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
5541 NameVals.clear();
5542 }
5543 }
5544
5545 if (Index.getBlockCount())
5547 ArrayRef<uint64_t>{Index.getBlockCount()});
5548
5549 Stream.ExitBlock();
5550}
5551
5552/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
5553/// current llvm version, and a record for the epoch number.
5556
5557 // Write the "user readable" string identifying the bitcode producer
5558 auto Abbv = std::make_shared<BitCodeAbbrev>();
5562 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5564 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5565
5566 // Write the epoch version
5567 Abbv = std::make_shared<BitCodeAbbrev>();
5570 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5571 constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
5572 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
5573 Stream.ExitBlock();
5574}
5575
5576void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5577 // Emit the module's hash.
5578 // MODULE_CODE_HASH: [5*i32]
5579 if (GenerateHash) {
5580 uint32_t Vals[5];
5581 Hasher.update(ArrayRef<uint8_t>(
5582 reinterpret_cast<const uint8_t *>(View.data()), View.size()));
5583 std::array<uint8_t, 20> Hash = Hasher.result();
5584 for (int Pos = 0; Pos < 20; Pos += 4) {
5585 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
5586 }
5587
5588 // Emit the finished record.
5589 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
5590
5591 if (ModHash)
5592 // Save the written hash value.
5593 llvm::copy(Vals, std::begin(*ModHash));
5594 }
5595}
5596
5597void ModuleBitcodeWriter::write() {
5599
5601 // We will want to write the module hash at this point. Block any flushing so
5602 // we can have access to the whole underlying data later.
5603 Stream.markAndBlockFlushing();
5604
5605 writeModuleVersion();
5606
5607 // Emit blockinfo, which defines the standard abbreviations etc.
5608 writeBlockInfo();
5609
5610 // Emit information describing all of the types in the module.
5611 writeTypeTable();
5612
5613 // Emit information about attribute groups.
5614 writeAttributeGroupTable();
5615
5616 // Emit information about parameter attributes.
5617 writeAttributeTable();
5618
5619 writeComdats();
5620
5621 // Emit top-level description of module, including target triple, inline asm,
5622 // descriptors for global variables, and function prototype info.
5623 writeModuleInfo();
5624
5625 // Emit constants.
5626 writeModuleConstants();
5627
5628 // Emit metadata kind names.
5629 writeModuleMetadataKinds();
5630
5631 // Emit metadata.
5632 writeModuleMetadata();
5633
5634 // Emit module-level use-lists.
5636 writeUseListBlock(nullptr);
5637
5638 writeOperandBundleTags();
5639 writeSyncScopeNames();
5640
5641 // Emit function bodies.
5642 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5643 for (const Function &F : M)
5644 if (!F.isDeclaration())
5645 writeFunction(F, FunctionToBitcodeIndex);
5646
5647 // Need to write after the above call to WriteFunction which populates
5648 // the summary information in the index.
5649 if (Index)
5650 writePerModuleGlobalValueSummary();
5651
5652 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5653
5654 writeModuleHash(Stream.getMarkedBufferAndResumeFlushing());
5655
5656 Stream.ExitBlock();
5657}
5658
5660 uint32_t &Position) {
5661 support::endian::write32le(&Buffer[Position], Value);
5662 Position += 4;
5663}
5664
5665/// If generating a bc file on darwin, we have to emit a
5666/// header and trailer to make it compatible with the system archiver. To do
5667/// this we emit the following header, and then emit a trailer that pads the
5668/// file out to be a multiple of 16 bytes.
5669///
5670/// struct bc_header {
5671/// uint32_t Magic; // 0x0B17C0DE
5672/// uint32_t Version; // Version, currently always 0.
5673/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
5674/// uint32_t BitcodeSize; // Size of traditional bitcode file.
5675/// uint32_t CPUType; // CPU specifier.
5676/// ... potentially more later ...
5677/// };
5679 const Triple &TT) {
5680 unsigned CPUType = ~0U;
5681
5682 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
5683 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
5684 // number from /usr/include/mach/machine.h. It is ok to reproduce the
5685 // specific constants here because they are implicitly part of the Darwin ABI.
5686 enum {
5687 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5688 DARWIN_CPU_TYPE_X86 = 7,
5689 DARWIN_CPU_TYPE_ARM = 12,
5690 DARWIN_CPU_TYPE_POWERPC = 18
5691 };
5692
5693 Triple::ArchType Arch = TT.getArch();
5694 if (Arch == Triple::x86_64)
5695 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5696 else if (Arch == Triple::x86)
5697 CPUType = DARWIN_CPU_TYPE_X86;
5698 else if (Arch == Triple::ppc)
5699 CPUType = DARWIN_CPU_TYPE_POWERPC;
5700 else if (Arch == Triple::ppc64)
5701 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5702 else if (Arch == Triple::arm || Arch == Triple::thumb)
5703 CPUType = DARWIN_CPU_TYPE_ARM;
5704
5705 // Traditional Bitcode starts after header.
5706 assert(Buffer.size() >= BWH_HeaderSize &&
5707 "Expected header size to be reserved");
5708 unsigned BCOffset = BWH_HeaderSize;
5709 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
5710
5711 // Write the magic and version.
5712 unsigned Position = 0;
5713 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
5714 writeInt32ToBuffer(0, Buffer, Position); // Version.
5715 writeInt32ToBuffer(BCOffset, Buffer, Position);
5716 writeInt32ToBuffer(BCSize, Buffer, Position);
5717 writeInt32ToBuffer(CPUType, Buffer, Position);
5718
5719 // If the file is not a multiple of 16 bytes, insert dummy padding.
5720 while (Buffer.size() & 15)
5721 Buffer.push_back(0);
5722}
5723
5724/// Helper to write the header common to all bitcode files.
5726 // Emit the file header.
5727 Stream.Emit((unsigned)'B', 8);
5728 Stream.Emit((unsigned)'C', 8);
5729 Stream.Emit(0x0, 4);
5730 Stream.Emit(0xC, 4);
5731 Stream.Emit(0xE, 4);
5732 Stream.Emit(0xD, 4);
5733}
5734
5736 : Stream(new BitstreamWriter(Buffer)) {
5737 writeBitcodeHeader(*Stream);
5738}
5739
5744
5746
5747void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
5748 Stream->EnterSubblock(Block, 3);
5749
5750 auto Abbv = std::make_shared<BitCodeAbbrev>();
5751 Abbv->Add(BitCodeAbbrevOp(Record));
5753 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
5754
5755 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
5756
5757 Stream->ExitBlock();
5758}
5759
5761 assert(!WroteStrtab && !WroteSymtab);
5762
5763 // If any module has module-level inline asm, we will require a registered asm
5764 // parser for the target so that we can create an accurate symbol table for
5765 // the module.
5766 for (Module *M : Mods) {
5767 if (M->getModuleInlineAsm().empty())
5768 continue;
5769
5770 std::string Err;
5771 const Triple TT(M->getTargetTriple());
5772 const Target *T = TargetRegistry::lookupTarget(TT, Err);
5773 if (!T || !T->hasMCAsmParser())
5774 return;
5775 }
5776
5777 WroteSymtab = true;
5778 SmallVector<char, 0> Symtab;
5779 // The irsymtab::build function may be unable to create a symbol table if the
5780 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
5781 // table is not required for correctness, but we still want to be able to
5782 // write malformed modules to bitcode files, so swallow the error.
5783 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
5784 consumeError(std::move(E));
5785 return;
5786 }
5787
5789 {Symtab.data(), Symtab.size()});
5790}
5791
5793 assert(!WroteStrtab);
5794
5795 std::vector<char> Strtab;
5796 StrtabBuilder.finalizeInOrder();
5797 Strtab.resize(StrtabBuilder.getSize());
5798 StrtabBuilder.write((uint8_t *)Strtab.data());
5799
5801 {Strtab.data(), Strtab.size()});
5802
5803 WroteStrtab = true;
5804}
5805
5807 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
5808 WroteStrtab = true;
5809}
5810
5812 bool ShouldPreserveUseListOrder,
5813 const ModuleSummaryIndex *Index,
5814 bool GenerateHash, ModuleHash *ModHash) {
5815 assert(!WroteStrtab);
5816
5817 // The Mods vector is used by irsymtab::build, which requires non-const
5818 // Modules in case it needs to materialize metadata. But the bitcode writer
5819 // requires that the module is materialized, so we can cast to non-const here,
5820 // after checking that it is in fact materialized.
5821 assert(M.isMaterialized());
5822 Mods.push_back(const_cast<Module *>(&M));
5823
5824 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5825 ShouldPreserveUseListOrder, Index,
5826 GenerateHash, ModHash);
5827 ModuleWriter.write();
5828}
5829
5831 const ModuleSummaryIndex *Index,
5832 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5833 const GVSummaryPtrSet *DecSummaries) {
5834 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5835 ModuleToSummariesForIndex);
5836 IndexWriter.write();
5837}
5838
5839/// Write the specified module to the specified output stream.
5841 bool ShouldPreserveUseListOrder,
5842 const ModuleSummaryIndex *Index,
5843 bool GenerateHash, ModuleHash *ModHash) {
5844 auto Write = [&](BitcodeWriter &Writer) {
5845 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5846 ModHash);
5847 Writer.writeSymtab();
5848 Writer.writeStrtab();
5849 };
5850 Triple TT(M.getTargetTriple());
5851 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5852 // If this is darwin or another generic macho target, reserve space for the
5853 // header. Note that the header is computed *after* the output is known, so
5854 // we currently explicitly use a buffer, write to it, and then subsequently
5855 // flush to Out.
5856 SmallVector<char, 0> Buffer;
5857 Buffer.reserve(256 * 1024);
5858 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
5859 BitcodeWriter Writer(Buffer);
5860 Write(Writer);
5861 emitDarwinBCHeaderAndTrailer(Buffer, TT);
5862 Out.write(Buffer.data(), Buffer.size());
5863 } else {
5864 BitcodeWriter Writer(Out);
5865 Write(Writer);
5866 }
5867}
5868
5869void IndexBitcodeWriter::write() {
5871
5872 writeModuleVersion();
5873
5874 // Write the module paths in the combined index.
5875 writeModStrings();
5876
5877 // Write the summary combined index records.
5878 writeCombinedGlobalValueSummary();
5879
5880 Stream.ExitBlock();
5881}
5882
5883// Write the specified module summary index to the given raw output stream,
5884// where it will be written in a new bitcode block. This is used when
5885// writing the combined index file for ThinLTO. When writing a subset of the
5886// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
5888 const ModuleSummaryIndex &Index, raw_ostream &Out,
5889 const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex,
5890 const GVSummaryPtrSet *DecSummaries) {
5891 SmallVector<char, 0> Buffer;
5892 Buffer.reserve(256 * 1024);
5893
5894 BitcodeWriter Writer(Buffer);
5895 Writer.writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5896 Writer.writeStrtab();
5897
5898 Out.write((char *)&Buffer.front(), Buffer.size());
5899}
5900
5901namespace {
5902
5903/// Class to manage the bitcode writing for a thin link bitcode file.
5904class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
5905 /// ModHash is for use in ThinLTO incremental build, generated while writing
5906 /// the module bitcode file.
5907 const ModuleHash *ModHash;
5908
5909public:
5910 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
5911 BitstreamWriter &Stream,
5912 const ModuleSummaryIndex &Index,
5913 const ModuleHash &ModHash)
5914 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5915 /*ShouldPreserveUseListOrder=*/false, &Index),
5916 ModHash(&ModHash) {}
5917
5918 void write();
5919
5920private:
5921 void writeSimplifiedModuleInfo();
5922};
5923
5924} // end anonymous namespace
5925
5926// This function writes a simpilified module info for thin link bitcode file.
5927// It only contains the source file name along with the name(the offset and
5928// size in strtab) and linkage for global values. For the global value info
5929// entry, in order to keep linkage at offset 5, there are three zeros used
5930// as padding.
5931void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5933 // Emit the module's source file name.
5934 {
5935 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
5937 if (Bits == SE_Char6)
5938 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
5939 else if (Bits == SE_Fixed7)
5940 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
5941
5942 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5943 auto Abbv = std::make_shared<BitCodeAbbrev>();
5946 Abbv->Add(AbbrevOpToUse);
5947 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
5948
5949 for (const auto P : M.getSourceFileName())
5950 Vals.push_back((unsigned char)P);
5951
5952 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
5953 Vals.clear();
5954 }
5955
5956 writeGUIDList();
5957
5958 // Emit the global variable information.
5959 for (const GlobalVariable &GV : M.globals()) {
5960 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
5961 Vals.push_back(StrtabBuilder.add(GV.getName()));
5962 Vals.push_back(GV.getName().size());
5963 Vals.push_back(0);
5964 Vals.push_back(0);
5965 Vals.push_back(0);
5966 Vals.push_back(getEncodedLinkage(GV));
5967
5969 Vals.clear();
5970 }
5971
5972 // Emit the function proto information.
5973 for (const Function &F : M) {
5974 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
5975 Vals.push_back(StrtabBuilder.add(F.getName()));
5976 Vals.push_back(F.getName().size());
5977 Vals.push_back(0);
5978 Vals.push_back(0);
5979 Vals.push_back(0);
5981
5983 Vals.clear();
5984 }
5985
5986 // Emit the alias information.
5987 for (const GlobalAlias &A : M.aliases()) {
5988 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
5989 Vals.push_back(StrtabBuilder.add(A.getName()));
5990 Vals.push_back(A.getName().size());
5991 Vals.push_back(0);
5992 Vals.push_back(0);
5993 Vals.push_back(0);
5995
5996 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
5997 Vals.clear();
5998 }
5999
6000 // Emit the ifunc information.
6001 for (const GlobalIFunc &I : M.ifuncs()) {
6002 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
6003 Vals.push_back(StrtabBuilder.add(I.getName()));
6004 Vals.push_back(I.getName().size());
6005 Vals.push_back(0);
6006 Vals.push_back(0);
6007 Vals.push_back(0);
6009
6010 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
6011 Vals.clear();
6012 }
6013}
6014
6015void ThinLinkBitcodeWriter::write() {
6017
6018 writeModuleVersion();
6019
6020 writeSimplifiedModuleInfo();
6021
6022 writePerModuleGlobalValueSummary();
6023
6024 // Write module hash.
6026
6027 Stream.ExitBlock();
6028}
6029
6031 const ModuleSummaryIndex &Index,
6032 const ModuleHash &ModHash) {
6033 assert(!WroteStrtab);
6034
6035 // The Mods vector is used by irsymtab::build, which requires non-const
6036 // Modules in case it needs to materialize metadata. But the bitcode writer
6037 // requires that the module is materialized, so we can cast to non-const here,
6038 // after checking that it is in fact materialized.
6039 assert(M.isMaterialized());
6040 Mods.push_back(const_cast<Module *>(&M));
6041
6042 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6043 ModHash);
6044 ThinLinkWriter.write();
6045}
6046
6047// Write the specified thin link bitcode file to the given raw output stream,
6048// where it will be written in a new bitcode block. This is used when
6049// writing the per-module index file for ThinLTO.
6051 const ModuleSummaryIndex &Index,
6052 const ModuleHash &ModHash) {
6053 SmallVector<char, 0> Buffer;
6054 Buffer.reserve(256 * 1024);
6055
6056 BitcodeWriter Writer(Buffer);
6057 Writer.writeThinLinkBitcode(M, Index, ModHash);
6058 Writer.writeSymtab();
6059 Writer.writeStrtab();
6060
6061 Out.write((char *)&Buffer.front(), Buffer.size());
6062}
6063
6064static const char *getSectionNameForBitcode(const Triple &T) {
6065 switch (T.getObjectFormat()) {
6066 case Triple::MachO:
6067 return "__LLVM,__bitcode";
6068 case Triple::COFF:
6069 case Triple::ELF:
6070 case Triple::Wasm:
6072 return ".llvmbc";
6073 case Triple::GOFF:
6074 llvm_unreachable("GOFF is not yet implemented");
6075 break;
6076 case Triple::SPIRV:
6077 if (T.getVendor() == Triple::AMD)
6078 return ".llvmbc";
6079 llvm_unreachable("SPIRV is not yet implemented");
6080 break;
6081 case Triple::XCOFF:
6082 llvm_unreachable("XCOFF is not yet implemented");
6083 break;
6085 llvm_unreachable("DXContainer is not yet implemented");
6086 break;
6087 }
6088 llvm_unreachable("Unimplemented ObjectFormatType");
6089}
6090
6091static const char *getSectionNameForCommandline(const Triple &T) {
6092 switch (T.getObjectFormat()) {
6093 case Triple::MachO:
6094 return "__LLVM,__cmdline";
6095 case Triple::COFF:
6096 case Triple::ELF:
6097 case Triple::Wasm:
6099 return ".llvmcmd";
6100 case Triple::GOFF:
6101 llvm_unreachable("GOFF is not yet implemented");
6102 break;
6103 case Triple::SPIRV:
6104 if (T.getVendor() == Triple::AMD)
6105 return ".llvmcmd";
6106 llvm_unreachable("SPIRV is not yet implemented");
6107 break;
6108 case Triple::XCOFF:
6109 llvm_unreachable("XCOFF is not yet implemented");
6110 break;
6112 llvm_unreachable("DXC is not yet implemented");
6113 break;
6114 }
6115 llvm_unreachable("Unimplemented ObjectFormatType");
6116}
6117
6119 bool EmbedBitcode, bool EmbedCmdline,
6120 const std::vector<uint8_t> &CmdArgs) {
6121 // Save llvm.compiler.used and remove it.
6124 GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
6125 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6126 : PointerType::getUnqual(M.getContext());
6127 for (auto *GV : UsedGlobals) {
6128 if (GV->getName() != "llvm.embedded.module" &&
6129 GV->getName() != "llvm.cmdline")
6130 UsedArray.push_back(
6132 }
6133 if (Used)
6134 Used->eraseFromParent();
6135
6136 // Embed the bitcode for the llvm module.
6137 std::string Data;
6138 ArrayRef<uint8_t> ModuleData;
6139 Triple T(M.getTargetTriple());
6140
6141 if (EmbedBitcode) {
6142 if (Buf.getBufferSize() == 0 ||
6143 !isBitcode((const unsigned char *)Buf.getBufferStart(),
6144 (const unsigned char *)Buf.getBufferEnd())) {
6145 // If the input is LLVM Assembly, bitcode is produced by serializing
6146 // the module. Use-lists order need to be preserved in this case.
6148 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
6149 ModuleData =
6150 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
6151 } else
6152 // If the input is LLVM bitcode, write the input byte stream directly.
6153 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
6154 Buf.getBufferSize());
6155 }
6156 llvm::Constant *ModuleConstant =
6157 llvm::ConstantDataArray::get(M.getContext(), ModuleData);
6159 M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
6160 ModuleConstant);
6162 // Set alignment to 1 to prevent padding between two contributions from input
6163 // sections after linking.
6164 GV->setAlignment(Align(1));
6165 UsedArray.push_back(
6167 if (llvm::GlobalVariable *Old =
6168 M.getGlobalVariable("llvm.embedded.module", true)) {
6169 assert(Old->hasZeroLiveUses() &&
6170 "llvm.embedded.module can only be used once in llvm.compiler.used");
6171 GV->takeName(Old);
6172 Old->eraseFromParent();
6173 } else {
6174 GV->setName("llvm.embedded.module");
6175 }
6176
6177 // Skip if only bitcode needs to be embedded.
6178 if (EmbedCmdline) {
6179 // Embed command-line options.
6180 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
6181 CmdArgs.size());
6182 llvm::Constant *CmdConstant =
6183 llvm::ConstantDataArray::get(M.getContext(), CmdData);
6184 GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
6186 CmdConstant);
6188 GV->setAlignment(Align(1));
6189 UsedArray.push_back(
6191 if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
6192 assert(Old->hasZeroLiveUses() &&
6193 "llvm.cmdline can only be used once in llvm.compiler.used");
6194 GV->takeName(Old);
6195 Old->eraseFromParent();
6196 } else {
6197 GV->setName("llvm.cmdline");
6198 }
6199 }
6200
6201 if (UsedArray.empty())
6202 return;
6203
6204 // Recreate llvm.compiler.used.
6205 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
6206 auto *NewUsed = new GlobalVariable(
6208 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
6209 NewUsed->setSection("llvm.metadata");
6210}
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_LIKELY_MODULE_LOCAL
@ 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,...