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