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