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