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