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