xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision 17ce89fa8016758be2ec879c5560e506cad4c362)
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 
13 #include "llvm/Bitcode/BitcodeWriter.h"
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/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Bitcode/BitcodeCommon.h"
28 #include "llvm/Bitcode/BitcodeReader.h"
29 #include "llvm/Bitcode/LLVMBitCodes.h"
30 #include "llvm/Bitstream/BitCodes.h"
31 #include "llvm/Bitstream/BitstreamWriter.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/IR/Attributes.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DebugInfoMetadata.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalObject.h"
45 #include "llvm/IR/GlobalValue.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/Instruction.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSummaryIndex.h"
55 #include "llvm/IR/Operator.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/UseListOrder.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/IR/ValueSymbolTable.h"
60 #include "llvm/MC/StringTableBuilder.h"
61 #include "llvm/MC/TargetRegistry.h"
62 #include "llvm/Object/IRSymtab.h"
63 #include "llvm/Support/AtomicOrdering.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Endian.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/SHA1.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstddef>
75 #include <cstdint>
76 #include <iterator>
77 #include <map>
78 #include <memory>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 static cl::opt<unsigned>
86     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
87                    cl::desc("Number of metadatas above which we emit an index "
88                             "to enable lazy-loading"));
89 static cl::opt<uint32_t> FlushThreshold(
90     "bitcode-flush-threshold", cl::Hidden, cl::init(512),
91     cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
92 
93 static cl::opt<bool> WriteRelBFToSummary(
94     "write-relbf-to-summary", cl::Hidden, cl::init(false),
95     cl::desc("Write relative block frequency to function summary "));
96 
97 extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
98 
99 namespace {
100 
101 /// These are manifest constants used by the bitcode writer. They do not need to
102 /// be kept in sync with the reader, but need to be consistent within this file.
103 enum {
104   // VALUE_SYMTAB_BLOCK abbrev id's.
105   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
106   VST_ENTRY_7_ABBREV,
107   VST_ENTRY_6_ABBREV,
108   VST_BBENTRY_6_ABBREV,
109 
110   // CONSTANTS_BLOCK abbrev id's.
111   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
112   CONSTANTS_INTEGER_ABBREV,
113   CONSTANTS_CE_CAST_Abbrev,
114   CONSTANTS_NULL_Abbrev,
115 
116   // FUNCTION_BLOCK abbrev id's.
117   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
118   FUNCTION_INST_UNOP_ABBREV,
119   FUNCTION_INST_UNOP_FLAGS_ABBREV,
120   FUNCTION_INST_BINOP_ABBREV,
121   FUNCTION_INST_BINOP_FLAGS_ABBREV,
122   FUNCTION_INST_CAST_ABBREV,
123   FUNCTION_INST_RET_VOID_ABBREV,
124   FUNCTION_INST_RET_VAL_ABBREV,
125   FUNCTION_INST_UNREACHABLE_ABBREV,
126   FUNCTION_INST_GEP_ABBREV,
127 };
128 
129 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
130 /// file type.
131 class BitcodeWriterBase {
132 protected:
133   /// The stream created and owned by the client.
134   BitstreamWriter &Stream;
135 
136   StringTableBuilder &StrtabBuilder;
137 
138 public:
139   /// Constructs a BitcodeWriterBase object that writes to the provided
140   /// \p Stream.
141   BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
142       : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
143 
144 protected:
145   void writeModuleVersion();
146 };
147 
148 void BitcodeWriterBase::writeModuleVersion() {
149   // VERSION: [version#]
150   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
151 }
152 
153 /// Base class to manage the module bitcode writing, currently subclassed for
154 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
155 class ModuleBitcodeWriterBase : public BitcodeWriterBase {
156 protected:
157   /// The Module to write to bitcode.
158   const Module &M;
159 
160   /// Enumerates ids for all values in the module.
161   ValueEnumerator VE;
162 
163   /// Optional per-module index to write for ThinLTO.
164   const ModuleSummaryIndex *Index;
165 
166   /// Map that holds the correspondence between GUIDs in the summary index,
167   /// that came from indirect call profiles, and a value id generated by this
168   /// class to use in the VST and summary block records.
169   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
170 
171   /// Tracks the last value id recorded in the GUIDToValueMap.
172   unsigned GlobalValueId;
173 
174   /// Saves the offset of the VSTOffset record that must eventually be
175   /// backpatched with the offset of the actual VST.
176   uint64_t VSTOffsetPlaceholder = 0;
177 
178 public:
179   /// Constructs a ModuleBitcodeWriterBase object for the given Module,
180   /// writing to the provided \p Buffer.
181   ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
182                           BitstreamWriter &Stream,
183                           bool ShouldPreserveUseListOrder,
184                           const ModuleSummaryIndex *Index)
185       : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
186         VE(M, ShouldPreserveUseListOrder), Index(Index) {
187     // Assign ValueIds to any callee values in the index that came from
188     // indirect call profiles and were recorded as a GUID not a Value*
189     // (which would have been assigned an ID by the ValueEnumerator).
190     // The starting ValueId is just after the number of values in the
191     // ValueEnumerator, so that they can be emitted in the VST.
192     GlobalValueId = VE.getValues().size();
193     if (!Index)
194       return;
195     for (const auto &GUIDSummaryLists : *Index)
196       // Examine all summaries for this GUID.
197       for (auto &Summary : GUIDSummaryLists.second.SummaryList)
198         if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
199           // For each call in the function summary, see if the call
200           // is to a GUID (which means it is for an indirect call,
201           // otherwise we would have a Value for it). If so, synthesize
202           // a value id.
203           for (auto &CallEdge : FS->calls())
204             if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
205               assignValueId(CallEdge.first.getGUID());
206   }
207 
208 protected:
209   void writePerModuleGlobalValueSummary();
210 
211 private:
212   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
213                                            GlobalValueSummary *Summary,
214                                            unsigned ValueID,
215                                            unsigned FSCallsAbbrev,
216                                            unsigned FSCallsProfileAbbrev,
217                                            const Function &F);
218   void writeModuleLevelReferences(const GlobalVariable &V,
219                                   SmallVector<uint64_t, 64> &NameVals,
220                                   unsigned FSModRefsAbbrev,
221                                   unsigned FSModVTableRefsAbbrev);
222 
223   void assignValueId(GlobalValue::GUID ValGUID) {
224     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
225   }
226 
227   unsigned getValueId(GlobalValue::GUID ValGUID) {
228     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
229     // Expect that any GUID value had a value Id assigned by an
230     // earlier call to assignValueId.
231     assert(VMI != GUIDToValueIdMap.end() &&
232            "GUID does not have assigned value Id");
233     return VMI->second;
234   }
235 
236   // Helper to get the valueId for the type of value recorded in VI.
237   unsigned getValueId(ValueInfo VI) {
238     if (!VI.haveGVs() || !VI.getValue())
239       return getValueId(VI.getGUID());
240     return VE.getValueID(VI.getValue());
241   }
242 
243   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
244 };
245 
246 /// Class to manage the bitcode writing for a module.
247 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
248   /// Pointer to the buffer allocated by caller for bitcode writing.
249   const SmallVectorImpl<char> &Buffer;
250 
251   /// True if a module hash record should be written.
252   bool GenerateHash;
253 
254   /// If non-null, when GenerateHash is true, the resulting hash is written
255   /// into ModHash.
256   ModuleHash *ModHash;
257 
258   SHA1 Hasher;
259 
260   /// The start bit of the identification block.
261   uint64_t BitcodeStartBit;
262 
263 public:
264   /// Constructs a ModuleBitcodeWriter object for the given Module,
265   /// writing to the provided \p Buffer.
266   ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
267                       StringTableBuilder &StrtabBuilder,
268                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
269                       const ModuleSummaryIndex *Index, bool GenerateHash,
270                       ModuleHash *ModHash = nullptr)
271       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
272                                 ShouldPreserveUseListOrder, Index),
273         Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
274         BitcodeStartBit(Stream.GetCurrentBitNo()) {}
275 
276   /// Emit the current module to the bitstream.
277   void write();
278 
279 private:
280   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
281 
282   size_t addToStrtab(StringRef Str);
283 
284   void writeAttributeGroupTable();
285   void writeAttributeTable();
286   void writeTypeTable();
287   void writeComdats();
288   void writeValueSymbolTableForwardDecl();
289   void writeModuleInfo();
290   void writeValueAsMetadata(const ValueAsMetadata *MD,
291                             SmallVectorImpl<uint64_t> &Record);
292   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
293                     unsigned Abbrev);
294   unsigned createDILocationAbbrev();
295   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
296                        unsigned &Abbrev);
297   unsigned createGenericDINodeAbbrev();
298   void writeGenericDINode(const GenericDINode *N,
299                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
300   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
301                        unsigned Abbrev);
302   void writeDIGenericSubrange(const DIGenericSubrange *N,
303                               SmallVectorImpl<uint64_t> &Record,
304                               unsigned Abbrev);
305   void writeDIEnumerator(const DIEnumerator *N,
306                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
307   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
308                         unsigned Abbrev);
309   void writeDIStringType(const DIStringType *N,
310                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
311   void writeDIDerivedType(const DIDerivedType *N,
312                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
313   void writeDICompositeType(const DICompositeType *N,
314                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
315   void writeDISubroutineType(const DISubroutineType *N,
316                              SmallVectorImpl<uint64_t> &Record,
317                              unsigned Abbrev);
318   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
319                    unsigned Abbrev);
320   void writeDICompileUnit(const DICompileUnit *N,
321                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
322   void writeDISubprogram(const DISubprogram *N,
323                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
324   void writeDILexicalBlock(const DILexicalBlock *N,
325                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
326   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
327                                SmallVectorImpl<uint64_t> &Record,
328                                unsigned Abbrev);
329   void writeDICommonBlock(const DICommonBlock *N,
330                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
331   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
332                         unsigned Abbrev);
333   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
334                     unsigned Abbrev);
335   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
336                         unsigned Abbrev);
337   void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record,
338                       unsigned Abbrev);
339   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
340                      unsigned Abbrev);
341   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
342                                     SmallVectorImpl<uint64_t> &Record,
343                                     unsigned Abbrev);
344   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
345                                      SmallVectorImpl<uint64_t> &Record,
346                                      unsigned Abbrev);
347   void writeDIGlobalVariable(const DIGlobalVariable *N,
348                              SmallVectorImpl<uint64_t> &Record,
349                              unsigned Abbrev);
350   void writeDILocalVariable(const DILocalVariable *N,
351                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
352   void writeDILabel(const DILabel *N,
353                     SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
354   void writeDIExpression(const DIExpression *N,
355                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
356   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
357                                        SmallVectorImpl<uint64_t> &Record,
358                                        unsigned Abbrev);
359   void writeDIObjCProperty(const DIObjCProperty *N,
360                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
361   void writeDIImportedEntity(const DIImportedEntity *N,
362                              SmallVectorImpl<uint64_t> &Record,
363                              unsigned Abbrev);
364   unsigned createNamedMetadataAbbrev();
365   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
366   unsigned createMetadataStringsAbbrev();
367   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
368                             SmallVectorImpl<uint64_t> &Record);
369   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
370                             SmallVectorImpl<uint64_t> &Record,
371                             std::vector<unsigned> *MDAbbrevs = nullptr,
372                             std::vector<uint64_t> *IndexPos = nullptr);
373   void writeModuleMetadata();
374   void writeFunctionMetadata(const Function &F);
375   void writeFunctionMetadataAttachment(const Function &F);
376   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
377                                     const GlobalObject &GO);
378   void writeModuleMetadataKinds();
379   void writeOperandBundleTags();
380   void writeSyncScopeNames();
381   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
382   void writeModuleConstants();
383   bool pushValueAndType(const Value *V, unsigned InstID,
384                         SmallVectorImpl<unsigned> &Vals);
385   void writeOperandBundles(const CallBase &CB, unsigned InstID);
386   void pushValue(const Value *V, unsigned InstID,
387                  SmallVectorImpl<unsigned> &Vals);
388   void pushValueSigned(const Value *V, unsigned InstID,
389                        SmallVectorImpl<uint64_t> &Vals);
390   void writeInstruction(const Instruction &I, unsigned InstID,
391                         SmallVectorImpl<unsigned> &Vals);
392   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
393   void writeGlobalValueSymbolTable(
394       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
395   void writeUseList(UseListOrder &&Order);
396   void writeUseListBlock(const Function *F);
397   void
398   writeFunction(const Function &F,
399                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
400   void writeBlockInfo();
401   void writeModuleHash(size_t BlockStartPos);
402 
403   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
404     return unsigned(SSID);
405   }
406 
407   unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
408 };
409 
410 /// Class to manage the bitcode writing for a combined index.
411 class IndexBitcodeWriter : public BitcodeWriterBase {
412   /// The combined index to write to bitcode.
413   const ModuleSummaryIndex &Index;
414 
415   /// When writing a subset of the index for distributed backends, client
416   /// provides a map of modules to the corresponding GUIDs/summaries to write.
417   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
418 
419   /// Map that holds the correspondence between the GUID used in the combined
420   /// index and a value id generated by this class to use in references.
421   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
422 
423   /// Tracks the last value id recorded in the GUIDToValueMap.
424   unsigned GlobalValueId = 0;
425 
426 public:
427   /// Constructs a IndexBitcodeWriter object for the given combined index,
428   /// writing to the provided \p Buffer. When writing a subset of the index
429   /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
430   IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
431                      const ModuleSummaryIndex &Index,
432                      const std::map<std::string, GVSummaryMapTy>
433                          *ModuleToSummariesForIndex = nullptr)
434       : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
435         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
436     // Assign unique value ids to all summaries to be written, for use
437     // in writing out the call graph edges. Save the mapping from GUID
438     // to the new global value id to use when writing those edges, which
439     // are currently saved in the index in terms of GUID.
440     forEachSummary([&](GVInfo I, bool) {
441       GUIDToValueIdMap[I.first] = ++GlobalValueId;
442     });
443   }
444 
445   /// The below iterator returns the GUID and associated summary.
446   using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
447 
448   /// Calls the callback for each value GUID and summary to be written to
449   /// bitcode. This hides the details of whether they are being pulled from the
450   /// entire index or just those in a provided ModuleToSummariesForIndex map.
451   template<typename Functor>
452   void forEachSummary(Functor Callback) {
453     if (ModuleToSummariesForIndex) {
454       for (auto &M : *ModuleToSummariesForIndex)
455         for (auto &Summary : M.second) {
456           Callback(Summary, false);
457           // Ensure aliasee is handled, e.g. for assigning a valueId,
458           // even if we are not importing the aliasee directly (the
459           // imported alias will contain a copy of aliasee).
460           if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
461             Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
462         }
463     } else {
464       for (auto &Summaries : Index)
465         for (auto &Summary : Summaries.second.SummaryList)
466           Callback({Summaries.first, Summary.get()}, false);
467     }
468   }
469 
470   /// Calls the callback for each entry in the modulePaths StringMap that
471   /// should be written to the module path string table. This hides the details
472   /// of whether they are being pulled from the entire index or just those in a
473   /// provided ModuleToSummariesForIndex map.
474   template <typename Functor> void forEachModule(Functor Callback) {
475     if (ModuleToSummariesForIndex) {
476       for (const auto &M : *ModuleToSummariesForIndex) {
477         const auto &MPI = Index.modulePaths().find(M.first);
478         if (MPI == Index.modulePaths().end()) {
479           // This should only happen if the bitcode file was empty, in which
480           // case we shouldn't be importing (the ModuleToSummariesForIndex
481           // would only include the module we are writing and index for).
482           assert(ModuleToSummariesForIndex->size() == 1);
483           continue;
484         }
485         Callback(*MPI);
486       }
487     } else {
488       for (const auto &MPSE : Index.modulePaths())
489         Callback(MPSE);
490     }
491   }
492 
493   /// Main entry point for writing a combined index to bitcode.
494   void write();
495 
496 private:
497   void writeModStrings();
498   void writeCombinedGlobalValueSummary();
499 
500   Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
501     auto VMI = GUIDToValueIdMap.find(ValGUID);
502     if (VMI == GUIDToValueIdMap.end())
503       return None;
504     return VMI->second;
505   }
506 
507   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
508 };
509 
510 } // end anonymous namespace
511 
512 static unsigned getEncodedCastOpcode(unsigned Opcode) {
513   switch (Opcode) {
514   default: llvm_unreachable("Unknown cast instruction!");
515   case Instruction::Trunc   : return bitc::CAST_TRUNC;
516   case Instruction::ZExt    : return bitc::CAST_ZEXT;
517   case Instruction::SExt    : return bitc::CAST_SEXT;
518   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
519   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
520   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
521   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
522   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
523   case Instruction::FPExt   : return bitc::CAST_FPEXT;
524   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
525   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
526   case Instruction::BitCast : return bitc::CAST_BITCAST;
527   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
528   }
529 }
530 
531 static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
532   switch (Opcode) {
533   default: llvm_unreachable("Unknown binary instruction!");
534   case Instruction::FNeg: return bitc::UNOP_FNEG;
535   }
536 }
537 
538 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
539   switch (Opcode) {
540   default: llvm_unreachable("Unknown binary instruction!");
541   case Instruction::Add:
542   case Instruction::FAdd: return bitc::BINOP_ADD;
543   case Instruction::Sub:
544   case Instruction::FSub: return bitc::BINOP_SUB;
545   case Instruction::Mul:
546   case Instruction::FMul: return bitc::BINOP_MUL;
547   case Instruction::UDiv: return bitc::BINOP_UDIV;
548   case Instruction::FDiv:
549   case Instruction::SDiv: return bitc::BINOP_SDIV;
550   case Instruction::URem: return bitc::BINOP_UREM;
551   case Instruction::FRem:
552   case Instruction::SRem: return bitc::BINOP_SREM;
553   case Instruction::Shl:  return bitc::BINOP_SHL;
554   case Instruction::LShr: return bitc::BINOP_LSHR;
555   case Instruction::AShr: return bitc::BINOP_ASHR;
556   case Instruction::And:  return bitc::BINOP_AND;
557   case Instruction::Or:   return bitc::BINOP_OR;
558   case Instruction::Xor:  return bitc::BINOP_XOR;
559   }
560 }
561 
562 static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
563   switch (Op) {
564   default: llvm_unreachable("Unknown RMW operation!");
565   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
566   case AtomicRMWInst::Add: return bitc::RMW_ADD;
567   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
568   case AtomicRMWInst::And: return bitc::RMW_AND;
569   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
570   case AtomicRMWInst::Or: return bitc::RMW_OR;
571   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
572   case AtomicRMWInst::Max: return bitc::RMW_MAX;
573   case AtomicRMWInst::Min: return bitc::RMW_MIN;
574   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
575   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
576   case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
577   case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
578   }
579 }
580 
581 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
582   switch (Ordering) {
583   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
584   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
585   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
586   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
587   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
588   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
589   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
590   }
591   llvm_unreachable("Invalid ordering");
592 }
593 
594 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
595                               StringRef Str, unsigned AbbrevToUse) {
596   SmallVector<unsigned, 64> Vals;
597 
598   // Code: [strchar x N]
599   for (char C : Str) {
600     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
601       AbbrevToUse = 0;
602     Vals.push_back(C);
603   }
604 
605   // Emit the finished record.
606   Stream.EmitRecord(Code, Vals, AbbrevToUse);
607 }
608 
609 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
610   switch (Kind) {
611   case Attribute::Alignment:
612     return bitc::ATTR_KIND_ALIGNMENT;
613   case Attribute::AllocSize:
614     return bitc::ATTR_KIND_ALLOC_SIZE;
615   case Attribute::AlwaysInline:
616     return bitc::ATTR_KIND_ALWAYS_INLINE;
617   case Attribute::ArgMemOnly:
618     return bitc::ATTR_KIND_ARGMEMONLY;
619   case Attribute::Builtin:
620     return bitc::ATTR_KIND_BUILTIN;
621   case Attribute::ByVal:
622     return bitc::ATTR_KIND_BY_VAL;
623   case Attribute::Convergent:
624     return bitc::ATTR_KIND_CONVERGENT;
625   case Attribute::InAlloca:
626     return bitc::ATTR_KIND_IN_ALLOCA;
627   case Attribute::Cold:
628     return bitc::ATTR_KIND_COLD;
629   case Attribute::DisableSanitizerInstrumentation:
630     return bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION;
631   case Attribute::Hot:
632     return bitc::ATTR_KIND_HOT;
633   case Attribute::ElementType:
634     return bitc::ATTR_KIND_ELEMENTTYPE;
635   case Attribute::InaccessibleMemOnly:
636     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
637   case Attribute::InaccessibleMemOrArgMemOnly:
638     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
639   case Attribute::InlineHint:
640     return bitc::ATTR_KIND_INLINE_HINT;
641   case Attribute::InReg:
642     return bitc::ATTR_KIND_IN_REG;
643   case Attribute::JumpTable:
644     return bitc::ATTR_KIND_JUMP_TABLE;
645   case Attribute::MinSize:
646     return bitc::ATTR_KIND_MIN_SIZE;
647   case Attribute::Naked:
648     return bitc::ATTR_KIND_NAKED;
649   case Attribute::Nest:
650     return bitc::ATTR_KIND_NEST;
651   case Attribute::NoAlias:
652     return bitc::ATTR_KIND_NO_ALIAS;
653   case Attribute::NoBuiltin:
654     return bitc::ATTR_KIND_NO_BUILTIN;
655   case Attribute::NoCallback:
656     return bitc::ATTR_KIND_NO_CALLBACK;
657   case Attribute::NoCapture:
658     return bitc::ATTR_KIND_NO_CAPTURE;
659   case Attribute::NoDuplicate:
660     return bitc::ATTR_KIND_NO_DUPLICATE;
661   case Attribute::NoFree:
662     return bitc::ATTR_KIND_NOFREE;
663   case Attribute::NoImplicitFloat:
664     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
665   case Attribute::NoInline:
666     return bitc::ATTR_KIND_NO_INLINE;
667   case Attribute::NoRecurse:
668     return bitc::ATTR_KIND_NO_RECURSE;
669   case Attribute::NoMerge:
670     return bitc::ATTR_KIND_NO_MERGE;
671   case Attribute::NonLazyBind:
672     return bitc::ATTR_KIND_NON_LAZY_BIND;
673   case Attribute::NonNull:
674     return bitc::ATTR_KIND_NON_NULL;
675   case Attribute::Dereferenceable:
676     return bitc::ATTR_KIND_DEREFERENCEABLE;
677   case Attribute::DereferenceableOrNull:
678     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
679   case Attribute::NoRedZone:
680     return bitc::ATTR_KIND_NO_RED_ZONE;
681   case Attribute::NoReturn:
682     return bitc::ATTR_KIND_NO_RETURN;
683   case Attribute::NoSync:
684     return bitc::ATTR_KIND_NOSYNC;
685   case Attribute::NoCfCheck:
686     return bitc::ATTR_KIND_NOCF_CHECK;
687   case Attribute::NoProfile:
688     return bitc::ATTR_KIND_NO_PROFILE;
689   case Attribute::NoUnwind:
690     return bitc::ATTR_KIND_NO_UNWIND;
691   case Attribute::NoSanitizeBounds:
692     return bitc::ATTR_KIND_NO_SANITIZE_BOUNDS;
693   case Attribute::NoSanitizeCoverage:
694     return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
695   case Attribute::NullPointerIsValid:
696     return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
697   case Attribute::OptForFuzzing:
698     return bitc::ATTR_KIND_OPT_FOR_FUZZING;
699   case Attribute::OptimizeForSize:
700     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
701   case Attribute::OptimizeNone:
702     return bitc::ATTR_KIND_OPTIMIZE_NONE;
703   case Attribute::ReadNone:
704     return bitc::ATTR_KIND_READ_NONE;
705   case Attribute::ReadOnly:
706     return bitc::ATTR_KIND_READ_ONLY;
707   case Attribute::Returned:
708     return bitc::ATTR_KIND_RETURNED;
709   case Attribute::ReturnsTwice:
710     return bitc::ATTR_KIND_RETURNS_TWICE;
711   case Attribute::SExt:
712     return bitc::ATTR_KIND_S_EXT;
713   case Attribute::Speculatable:
714     return bitc::ATTR_KIND_SPECULATABLE;
715   case Attribute::StackAlignment:
716     return bitc::ATTR_KIND_STACK_ALIGNMENT;
717   case Attribute::StackProtect:
718     return bitc::ATTR_KIND_STACK_PROTECT;
719   case Attribute::StackProtectReq:
720     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
721   case Attribute::StackProtectStrong:
722     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
723   case Attribute::SafeStack:
724     return bitc::ATTR_KIND_SAFESTACK;
725   case Attribute::ShadowCallStack:
726     return bitc::ATTR_KIND_SHADOWCALLSTACK;
727   case Attribute::StrictFP:
728     return bitc::ATTR_KIND_STRICT_FP;
729   case Attribute::StructRet:
730     return bitc::ATTR_KIND_STRUCT_RET;
731   case Attribute::SanitizeAddress:
732     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
733   case Attribute::SanitizeHWAddress:
734     return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
735   case Attribute::SanitizeThread:
736     return bitc::ATTR_KIND_SANITIZE_THREAD;
737   case Attribute::SanitizeMemory:
738     return bitc::ATTR_KIND_SANITIZE_MEMORY;
739   case Attribute::SpeculativeLoadHardening:
740     return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
741   case Attribute::SwiftError:
742     return bitc::ATTR_KIND_SWIFT_ERROR;
743   case Attribute::SwiftSelf:
744     return bitc::ATTR_KIND_SWIFT_SELF;
745   case Attribute::SwiftAsync:
746     return bitc::ATTR_KIND_SWIFT_ASYNC;
747   case Attribute::UWTable:
748     return bitc::ATTR_KIND_UW_TABLE;
749   case Attribute::VScaleRange:
750     return bitc::ATTR_KIND_VSCALE_RANGE;
751   case Attribute::WillReturn:
752     return bitc::ATTR_KIND_WILLRETURN;
753   case Attribute::WriteOnly:
754     return bitc::ATTR_KIND_WRITEONLY;
755   case Attribute::ZExt:
756     return bitc::ATTR_KIND_Z_EXT;
757   case Attribute::ImmArg:
758     return bitc::ATTR_KIND_IMMARG;
759   case Attribute::SanitizeMemTag:
760     return bitc::ATTR_KIND_SANITIZE_MEMTAG;
761   case Attribute::Preallocated:
762     return bitc::ATTR_KIND_PREALLOCATED;
763   case Attribute::NoUndef:
764     return bitc::ATTR_KIND_NOUNDEF;
765   case Attribute::ByRef:
766     return bitc::ATTR_KIND_BYREF;
767   case Attribute::MustProgress:
768     return bitc::ATTR_KIND_MUSTPROGRESS;
769   case Attribute::EndAttrKinds:
770     llvm_unreachable("Can not encode end-attribute kinds marker.");
771   case Attribute::None:
772     llvm_unreachable("Can not encode none-attribute.");
773   case Attribute::EmptyKey:
774   case Attribute::TombstoneKey:
775     llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
776   }
777 
778   llvm_unreachable("Trying to encode unknown attribute");
779 }
780 
781 void ModuleBitcodeWriter::writeAttributeGroupTable() {
782   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
783       VE.getAttributeGroups();
784   if (AttrGrps.empty()) return;
785 
786   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
787 
788   SmallVector<uint64_t, 64> Record;
789   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
790     unsigned AttrListIndex = Pair.first;
791     AttributeSet AS = Pair.second;
792     Record.push_back(VE.getAttributeGroupID(Pair));
793     Record.push_back(AttrListIndex);
794 
795     for (Attribute Attr : AS) {
796       if (Attr.isEnumAttribute()) {
797         Record.push_back(0);
798         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
799       } else if (Attr.isIntAttribute()) {
800         Record.push_back(1);
801         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
802         Record.push_back(Attr.getValueAsInt());
803       } else if (Attr.isStringAttribute()) {
804         StringRef Kind = Attr.getKindAsString();
805         StringRef Val = Attr.getValueAsString();
806 
807         Record.push_back(Val.empty() ? 3 : 4);
808         Record.append(Kind.begin(), Kind.end());
809         Record.push_back(0);
810         if (!Val.empty()) {
811           Record.append(Val.begin(), Val.end());
812           Record.push_back(0);
813         }
814       } else {
815         assert(Attr.isTypeAttribute());
816         Type *Ty = Attr.getValueAsType();
817         Record.push_back(Ty ? 6 : 5);
818         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
819         if (Ty)
820           Record.push_back(VE.getTypeID(Attr.getValueAsType()));
821       }
822     }
823 
824     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
825     Record.clear();
826   }
827 
828   Stream.ExitBlock();
829 }
830 
831 void ModuleBitcodeWriter::writeAttributeTable() {
832   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
833   if (Attrs.empty()) return;
834 
835   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
836 
837   SmallVector<uint64_t, 64> Record;
838   for (const AttributeList &AL : Attrs) {
839     for (unsigned i : AL.indexes()) {
840       AttributeSet AS = AL.getAttributes(i);
841       if (AS.hasAttributes())
842         Record.push_back(VE.getAttributeGroupID({i, AS}));
843     }
844 
845     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
846     Record.clear();
847   }
848 
849   Stream.ExitBlock();
850 }
851 
852 /// WriteTypeTable - Write out the type table for a module.
853 void ModuleBitcodeWriter::writeTypeTable() {
854   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
855 
856   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
857   SmallVector<uint64_t, 64> TypeVals;
858 
859   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
860 
861   // Abbrev for TYPE_CODE_POINTER.
862   auto Abbv = std::make_shared<BitCodeAbbrev>();
863   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
864   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
865   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
866   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
867 
868   // Abbrev for TYPE_CODE_OPAQUE_POINTER.
869   Abbv = std::make_shared<BitCodeAbbrev>();
870   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_OPAQUE_POINTER));
871   Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
872   unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
873 
874   // Abbrev for TYPE_CODE_FUNCTION.
875   Abbv = std::make_shared<BitCodeAbbrev>();
876   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
877   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
878   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
879   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
880   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
881 
882   // Abbrev for TYPE_CODE_STRUCT_ANON.
883   Abbv = std::make_shared<BitCodeAbbrev>();
884   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
885   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
886   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
887   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
888   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
889 
890   // Abbrev for TYPE_CODE_STRUCT_NAME.
891   Abbv = std::make_shared<BitCodeAbbrev>();
892   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
893   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
894   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
895   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
896 
897   // Abbrev for TYPE_CODE_STRUCT_NAMED.
898   Abbv = std::make_shared<BitCodeAbbrev>();
899   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
900   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
901   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
902   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
903   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
904 
905   // Abbrev for TYPE_CODE_ARRAY.
906   Abbv = std::make_shared<BitCodeAbbrev>();
907   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
908   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
909   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
910   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
911 
912   // Emit an entry count so the reader can reserve space.
913   TypeVals.push_back(TypeList.size());
914   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
915   TypeVals.clear();
916 
917   // Loop over all of the types, emitting each in turn.
918   for (Type *T : TypeList) {
919     int AbbrevToUse = 0;
920     unsigned Code = 0;
921 
922     switch (T->getTypeID()) {
923     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
924     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
925     case Type::BFloatTyID:    Code = bitc::TYPE_CODE_BFLOAT;    break;
926     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
927     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
928     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
929     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
930     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
931     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
932     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
933     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
934     case Type::X86_AMXTyID:   Code = bitc::TYPE_CODE_X86_AMX;   break;
935     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
936     case Type::IntegerTyID:
937       // INTEGER: [width]
938       Code = bitc::TYPE_CODE_INTEGER;
939       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
940       break;
941     case Type::PointerTyID: {
942       PointerType *PTy = cast<PointerType>(T);
943       unsigned AddressSpace = PTy->getAddressSpace();
944       if (PTy->isOpaque()) {
945         // OPAQUE_POINTER: [address space]
946         Code = bitc::TYPE_CODE_OPAQUE_POINTER;
947         TypeVals.push_back(AddressSpace);
948         if (AddressSpace == 0)
949           AbbrevToUse = OpaquePtrAbbrev;
950       } else {
951         // POINTER: [pointee type, address space]
952         Code = bitc::TYPE_CODE_POINTER;
953         TypeVals.push_back(VE.getTypeID(PTy->getNonOpaquePointerElementType()));
954         TypeVals.push_back(AddressSpace);
955         if (AddressSpace == 0)
956           AbbrevToUse = PtrAbbrev;
957       }
958       break;
959     }
960     case Type::FunctionTyID: {
961       FunctionType *FT = cast<FunctionType>(T);
962       // FUNCTION: [isvararg, retty, paramty x N]
963       Code = bitc::TYPE_CODE_FUNCTION;
964       TypeVals.push_back(FT->isVarArg());
965       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
966       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
967         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
968       AbbrevToUse = FunctionAbbrev;
969       break;
970     }
971     case Type::StructTyID: {
972       StructType *ST = cast<StructType>(T);
973       // STRUCT: [ispacked, eltty x N]
974       TypeVals.push_back(ST->isPacked());
975       // Output all of the element types.
976       for (Type *ET : ST->elements())
977         TypeVals.push_back(VE.getTypeID(ET));
978 
979       if (ST->isLiteral()) {
980         Code = bitc::TYPE_CODE_STRUCT_ANON;
981         AbbrevToUse = StructAnonAbbrev;
982       } else {
983         if (ST->isOpaque()) {
984           Code = bitc::TYPE_CODE_OPAQUE;
985         } else {
986           Code = bitc::TYPE_CODE_STRUCT_NAMED;
987           AbbrevToUse = StructNamedAbbrev;
988         }
989 
990         // Emit the name if it is present.
991         if (!ST->getName().empty())
992           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
993                             StructNameAbbrev);
994       }
995       break;
996     }
997     case Type::ArrayTyID: {
998       ArrayType *AT = cast<ArrayType>(T);
999       // ARRAY: [numelts, eltty]
1000       Code = bitc::TYPE_CODE_ARRAY;
1001       TypeVals.push_back(AT->getNumElements());
1002       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1003       AbbrevToUse = ArrayAbbrev;
1004       break;
1005     }
1006     case Type::FixedVectorTyID:
1007     case Type::ScalableVectorTyID: {
1008       VectorType *VT = cast<VectorType>(T);
1009       // VECTOR [numelts, eltty] or
1010       //        [numelts, eltty, scalable]
1011       Code = bitc::TYPE_CODE_VECTOR;
1012       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1013       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1014       if (isa<ScalableVectorType>(VT))
1015         TypeVals.push_back(true);
1016       break;
1017     }
1018     }
1019 
1020     // Emit the finished record.
1021     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1022     TypeVals.clear();
1023   }
1024 
1025   Stream.ExitBlock();
1026 }
1027 
1028 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1029   switch (Linkage) {
1030   case GlobalValue::ExternalLinkage:
1031     return 0;
1032   case GlobalValue::WeakAnyLinkage:
1033     return 16;
1034   case GlobalValue::AppendingLinkage:
1035     return 2;
1036   case GlobalValue::InternalLinkage:
1037     return 3;
1038   case GlobalValue::LinkOnceAnyLinkage:
1039     return 18;
1040   case GlobalValue::ExternalWeakLinkage:
1041     return 7;
1042   case GlobalValue::CommonLinkage:
1043     return 8;
1044   case GlobalValue::PrivateLinkage:
1045     return 9;
1046   case GlobalValue::WeakODRLinkage:
1047     return 17;
1048   case GlobalValue::LinkOnceODRLinkage:
1049     return 19;
1050   case GlobalValue::AvailableExternallyLinkage:
1051     return 12;
1052   }
1053   llvm_unreachable("Invalid linkage");
1054 }
1055 
1056 static unsigned getEncodedLinkage(const GlobalValue &GV) {
1057   return getEncodedLinkage(GV.getLinkage());
1058 }
1059 
1060 static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
1061   uint64_t RawFlags = 0;
1062   RawFlags |= Flags.ReadNone;
1063   RawFlags |= (Flags.ReadOnly << 1);
1064   RawFlags |= (Flags.NoRecurse << 2);
1065   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1066   RawFlags |= (Flags.NoInline << 4);
1067   RawFlags |= (Flags.AlwaysInline << 5);
1068   RawFlags |= (Flags.NoUnwind << 6);
1069   RawFlags |= (Flags.MayThrow << 7);
1070   RawFlags |= (Flags.HasUnknownCall << 8);
1071   RawFlags |= (Flags.MustBeUnreachable << 9);
1072   return RawFlags;
1073 }
1074 
1075 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1076 // in BitcodeReader.cpp.
1077 static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
1078   uint64_t RawFlags = 0;
1079 
1080   RawFlags |= Flags.NotEligibleToImport; // bool
1081   RawFlags |= (Flags.Live << 1);
1082   RawFlags |= (Flags.DSOLocal << 2);
1083   RawFlags |= (Flags.CanAutoHide << 3);
1084 
1085   // Linkage don't need to be remapped at that time for the summary. Any future
1086   // change to the getEncodedLinkage() function will need to be taken into
1087   // account here as well.
1088   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1089 
1090   RawFlags |= (Flags.Visibility << 8); // 2 bits
1091 
1092   return RawFlags;
1093 }
1094 
1095 static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
1096   uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1097                       (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1098   return RawFlags;
1099 }
1100 
1101 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1102   switch (GV.getVisibility()) {
1103   case GlobalValue::DefaultVisibility:   return 0;
1104   case GlobalValue::HiddenVisibility:    return 1;
1105   case GlobalValue::ProtectedVisibility: return 2;
1106   }
1107   llvm_unreachable("Invalid visibility");
1108 }
1109 
1110 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1111   switch (GV.getDLLStorageClass()) {
1112   case GlobalValue::DefaultStorageClass:   return 0;
1113   case GlobalValue::DLLImportStorageClass: return 1;
1114   case GlobalValue::DLLExportStorageClass: return 2;
1115   }
1116   llvm_unreachable("Invalid DLL storage class");
1117 }
1118 
1119 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1120   switch (GV.getThreadLocalMode()) {
1121     case GlobalVariable::NotThreadLocal:         return 0;
1122     case GlobalVariable::GeneralDynamicTLSModel: return 1;
1123     case GlobalVariable::LocalDynamicTLSModel:   return 2;
1124     case GlobalVariable::InitialExecTLSModel:    return 3;
1125     case GlobalVariable::LocalExecTLSModel:      return 4;
1126   }
1127   llvm_unreachable("Invalid TLS model");
1128 }
1129 
1130 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1131   switch (C.getSelectionKind()) {
1132   case Comdat::Any:
1133     return bitc::COMDAT_SELECTION_KIND_ANY;
1134   case Comdat::ExactMatch:
1135     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1136   case Comdat::Largest:
1137     return bitc::COMDAT_SELECTION_KIND_LARGEST;
1138   case Comdat::NoDeduplicate:
1139     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1140   case Comdat::SameSize:
1141     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1142   }
1143   llvm_unreachable("Invalid selection kind");
1144 }
1145 
1146 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1147   switch (GV.getUnnamedAddr()) {
1148   case GlobalValue::UnnamedAddr::None:   return 0;
1149   case GlobalValue::UnnamedAddr::Local:  return 2;
1150   case GlobalValue::UnnamedAddr::Global: return 1;
1151   }
1152   llvm_unreachable("Invalid unnamed_addr");
1153 }
1154 
1155 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1156   if (GenerateHash)
1157     Hasher.update(Str);
1158   return StrtabBuilder.add(Str);
1159 }
1160 
1161 void ModuleBitcodeWriter::writeComdats() {
1162   SmallVector<unsigned, 64> Vals;
1163   for (const Comdat *C : VE.getComdats()) {
1164     // COMDAT: [strtab offset, strtab size, selection_kind]
1165     Vals.push_back(addToStrtab(C->getName()));
1166     Vals.push_back(C->getName().size());
1167     Vals.push_back(getEncodedComdatSelectionKind(*C));
1168     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1169     Vals.clear();
1170   }
1171 }
1172 
1173 /// Write a record that will eventually hold the word offset of the
1174 /// module-level VST. For now the offset is 0, which will be backpatched
1175 /// after the real VST is written. Saves the bit offset to backpatch.
1176 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1177   // Write a placeholder value in for the offset of the real VST,
1178   // which is written after the function blocks so that it can include
1179   // the offset of each function. The placeholder offset will be
1180   // updated when the real VST is written.
1181   auto Abbv = std::make_shared<BitCodeAbbrev>();
1182   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1183   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1184   // hold the real VST offset. Must use fixed instead of VBR as we don't
1185   // know how many VBR chunks to reserve ahead of time.
1186   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1187   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1188 
1189   // Emit the placeholder
1190   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1191   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1192 
1193   // Compute and save the bit offset to the placeholder, which will be
1194   // patched when the real VST is written. We can simply subtract the 32-bit
1195   // fixed size from the current bit number to get the location to backpatch.
1196   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1197 }
1198 
1199 enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1200 
1201 /// Determine the encoding to use for the given string name and length.
1202 static StringEncoding getStringEncoding(StringRef Str) {
1203   bool isChar6 = true;
1204   for (char C : Str) {
1205     if (isChar6)
1206       isChar6 = BitCodeAbbrevOp::isChar6(C);
1207     if ((unsigned char)C & 128)
1208       // don't bother scanning the rest.
1209       return SE_Fixed8;
1210   }
1211   if (isChar6)
1212     return SE_Char6;
1213   return SE_Fixed7;
1214 }
1215 
1216 /// Emit top-level description of module, including target triple, inline asm,
1217 /// descriptors for global variables, and function prototype info.
1218 /// Returns the bit offset to backpatch with the location of the real VST.
1219 void ModuleBitcodeWriter::writeModuleInfo() {
1220   // Emit various pieces of data attached to a module.
1221   if (!M.getTargetTriple().empty())
1222     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1223                       0 /*TODO*/);
1224   const std::string &DL = M.getDataLayoutStr();
1225   if (!DL.empty())
1226     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1227   if (!M.getModuleInlineAsm().empty())
1228     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1229                       0 /*TODO*/);
1230 
1231   // Emit information about sections and GC, computing how many there are. Also
1232   // compute the maximum alignment value.
1233   std::map<std::string, unsigned> SectionMap;
1234   std::map<std::string, unsigned> GCMap;
1235   MaybeAlign MaxAlignment;
1236   unsigned MaxGlobalType = 0;
1237   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1238     if (A)
1239       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1240   };
1241   for (const GlobalVariable &GV : M.globals()) {
1242     UpdateMaxAlignment(GV.getAlign());
1243     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1244     if (GV.hasSection()) {
1245       // Give section names unique ID's.
1246       unsigned &Entry = SectionMap[std::string(GV.getSection())];
1247       if (!Entry) {
1248         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1249                           0 /*TODO*/);
1250         Entry = SectionMap.size();
1251       }
1252     }
1253   }
1254   for (const Function &F : M) {
1255     UpdateMaxAlignment(F.getAlign());
1256     if (F.hasSection()) {
1257       // Give section names unique ID's.
1258       unsigned &Entry = SectionMap[std::string(F.getSection())];
1259       if (!Entry) {
1260         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1261                           0 /*TODO*/);
1262         Entry = SectionMap.size();
1263       }
1264     }
1265     if (F.hasGC()) {
1266       // Same for GC names.
1267       unsigned &Entry = GCMap[F.getGC()];
1268       if (!Entry) {
1269         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1270                           0 /*TODO*/);
1271         Entry = GCMap.size();
1272       }
1273     }
1274   }
1275 
1276   // Emit abbrev for globals, now that we know # sections and max alignment.
1277   unsigned SimpleGVarAbbrev = 0;
1278   if (!M.global_empty()) {
1279     // Add an abbrev for common globals with no visibility or thread localness.
1280     auto Abbv = std::make_shared<BitCodeAbbrev>();
1281     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1282     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1283     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1284     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1285                               Log2_32_Ceil(MaxGlobalType+1)));
1286     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
1287                                                            //| explicitType << 1
1288                                                            //| constant
1289     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
1290     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1291     if (!MaxAlignment)                                     // Alignment.
1292       Abbv->Add(BitCodeAbbrevOp(0));
1293     else {
1294       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1295       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1296                                Log2_32_Ceil(MaxEncAlignment+1)));
1297     }
1298     if (SectionMap.empty())                                    // Section.
1299       Abbv->Add(BitCodeAbbrevOp(0));
1300     else
1301       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1302                                Log2_32_Ceil(SectionMap.size()+1)));
1303     // Don't bother emitting vis + thread local.
1304     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1305   }
1306 
1307   SmallVector<unsigned, 64> Vals;
1308   // Emit the module's source file name.
1309   {
1310     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1311     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1312     if (Bits == SE_Char6)
1313       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1314     else if (Bits == SE_Fixed7)
1315       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1316 
1317     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1318     auto Abbv = std::make_shared<BitCodeAbbrev>();
1319     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1320     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1321     Abbv->Add(AbbrevOpToUse);
1322     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1323 
1324     for (const auto P : M.getSourceFileName())
1325       Vals.push_back((unsigned char)P);
1326 
1327     // Emit the finished record.
1328     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1329     Vals.clear();
1330   }
1331 
1332   // Emit the global variable information.
1333   for (const GlobalVariable &GV : M.globals()) {
1334     unsigned AbbrevToUse = 0;
1335 
1336     // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1337     //             linkage, alignment, section, visibility, threadlocal,
1338     //             unnamed_addr, externally_initialized, dllstorageclass,
1339     //             comdat, attributes, DSO_Local]
1340     Vals.push_back(addToStrtab(GV.getName()));
1341     Vals.push_back(GV.getName().size());
1342     Vals.push_back(VE.getTypeID(GV.getValueType()));
1343     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1344     Vals.push_back(GV.isDeclaration() ? 0 :
1345                    (VE.getValueID(GV.getInitializer()) + 1));
1346     Vals.push_back(getEncodedLinkage(GV));
1347     Vals.push_back(getEncodedAlign(GV.getAlign()));
1348     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1349                                    : 0);
1350     if (GV.isThreadLocal() ||
1351         GV.getVisibility() != GlobalValue::DefaultVisibility ||
1352         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1353         GV.isExternallyInitialized() ||
1354         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1355         GV.hasComdat() ||
1356         GV.hasAttributes() ||
1357         GV.isDSOLocal() ||
1358         GV.hasPartition()) {
1359       Vals.push_back(getEncodedVisibility(GV));
1360       Vals.push_back(getEncodedThreadLocalMode(GV));
1361       Vals.push_back(getEncodedUnnamedAddr(GV));
1362       Vals.push_back(GV.isExternallyInitialized());
1363       Vals.push_back(getEncodedDLLStorageClass(GV));
1364       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1365 
1366       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1367       Vals.push_back(VE.getAttributeListID(AL));
1368 
1369       Vals.push_back(GV.isDSOLocal());
1370       Vals.push_back(addToStrtab(GV.getPartition()));
1371       Vals.push_back(GV.getPartition().size());
1372     } else {
1373       AbbrevToUse = SimpleGVarAbbrev;
1374     }
1375 
1376     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1377     Vals.clear();
1378   }
1379 
1380   // Emit the function proto information.
1381   for (const Function &F : M) {
1382     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
1383     //             linkage, paramattrs, alignment, section, visibility, gc,
1384     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
1385     //             prefixdata, personalityfn, DSO_Local, addrspace]
1386     Vals.push_back(addToStrtab(F.getName()));
1387     Vals.push_back(F.getName().size());
1388     Vals.push_back(VE.getTypeID(F.getFunctionType()));
1389     Vals.push_back(F.getCallingConv());
1390     Vals.push_back(F.isDeclaration());
1391     Vals.push_back(getEncodedLinkage(F));
1392     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1393     Vals.push_back(getEncodedAlign(F.getAlign()));
1394     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1395                                   : 0);
1396     Vals.push_back(getEncodedVisibility(F));
1397     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1398     Vals.push_back(getEncodedUnnamedAddr(F));
1399     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1400                                        : 0);
1401     Vals.push_back(getEncodedDLLStorageClass(F));
1402     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1403     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1404                                      : 0);
1405     Vals.push_back(
1406         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1407 
1408     Vals.push_back(F.isDSOLocal());
1409     Vals.push_back(F.getAddressSpace());
1410     Vals.push_back(addToStrtab(F.getPartition()));
1411     Vals.push_back(F.getPartition().size());
1412 
1413     unsigned AbbrevToUse = 0;
1414     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1415     Vals.clear();
1416   }
1417 
1418   // Emit the alias information.
1419   for (const GlobalAlias &A : M.aliases()) {
1420     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1421     //         visibility, dllstorageclass, threadlocal, unnamed_addr,
1422     //         DSO_Local]
1423     Vals.push_back(addToStrtab(A.getName()));
1424     Vals.push_back(A.getName().size());
1425     Vals.push_back(VE.getTypeID(A.getValueType()));
1426     Vals.push_back(A.getType()->getAddressSpace());
1427     Vals.push_back(VE.getValueID(A.getAliasee()));
1428     Vals.push_back(getEncodedLinkage(A));
1429     Vals.push_back(getEncodedVisibility(A));
1430     Vals.push_back(getEncodedDLLStorageClass(A));
1431     Vals.push_back(getEncodedThreadLocalMode(A));
1432     Vals.push_back(getEncodedUnnamedAddr(A));
1433     Vals.push_back(A.isDSOLocal());
1434     Vals.push_back(addToStrtab(A.getPartition()));
1435     Vals.push_back(A.getPartition().size());
1436 
1437     unsigned AbbrevToUse = 0;
1438     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1439     Vals.clear();
1440   }
1441 
1442   // Emit the ifunc information.
1443   for (const GlobalIFunc &I : M.ifuncs()) {
1444     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1445     //         val#, linkage, visibility, DSO_Local]
1446     Vals.push_back(addToStrtab(I.getName()));
1447     Vals.push_back(I.getName().size());
1448     Vals.push_back(VE.getTypeID(I.getValueType()));
1449     Vals.push_back(I.getType()->getAddressSpace());
1450     Vals.push_back(VE.getValueID(I.getResolver()));
1451     Vals.push_back(getEncodedLinkage(I));
1452     Vals.push_back(getEncodedVisibility(I));
1453     Vals.push_back(I.isDSOLocal());
1454     Vals.push_back(addToStrtab(I.getPartition()));
1455     Vals.push_back(I.getPartition().size());
1456     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1457     Vals.clear();
1458   }
1459 
1460   writeValueSymbolTableForwardDecl();
1461 }
1462 
1463 static uint64_t getOptimizationFlags(const Value *V) {
1464   uint64_t Flags = 0;
1465 
1466   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1467     if (OBO->hasNoSignedWrap())
1468       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1469     if (OBO->hasNoUnsignedWrap())
1470       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1471   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1472     if (PEO->isExact())
1473       Flags |= 1 << bitc::PEO_EXACT;
1474   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1475     if (FPMO->hasAllowReassoc())
1476       Flags |= bitc::AllowReassoc;
1477     if (FPMO->hasNoNaNs())
1478       Flags |= bitc::NoNaNs;
1479     if (FPMO->hasNoInfs())
1480       Flags |= bitc::NoInfs;
1481     if (FPMO->hasNoSignedZeros())
1482       Flags |= bitc::NoSignedZeros;
1483     if (FPMO->hasAllowReciprocal())
1484       Flags |= bitc::AllowReciprocal;
1485     if (FPMO->hasAllowContract())
1486       Flags |= bitc::AllowContract;
1487     if (FPMO->hasApproxFunc())
1488       Flags |= bitc::ApproxFunc;
1489   }
1490 
1491   return Flags;
1492 }
1493 
1494 void ModuleBitcodeWriter::writeValueAsMetadata(
1495     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1496   // Mimic an MDNode with a value as one operand.
1497   Value *V = MD->getValue();
1498   Record.push_back(VE.getTypeID(V->getType()));
1499   Record.push_back(VE.getValueID(V));
1500   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1501   Record.clear();
1502 }
1503 
1504 void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1505                                        SmallVectorImpl<uint64_t> &Record,
1506                                        unsigned Abbrev) {
1507   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1508     Metadata *MD = N->getOperand(i);
1509     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1510            "Unexpected function-local metadata");
1511     Record.push_back(VE.getMetadataOrNullID(MD));
1512   }
1513   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1514                                     : bitc::METADATA_NODE,
1515                     Record, Abbrev);
1516   Record.clear();
1517 }
1518 
1519 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1520   // Assume the column is usually under 128, and always output the inlined-at
1521   // location (it's never more expensive than building an array size 1).
1522   auto Abbv = std::make_shared<BitCodeAbbrev>();
1523   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1524   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1525   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1526   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1527   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1528   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1529   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1530   return Stream.EmitAbbrev(std::move(Abbv));
1531 }
1532 
1533 void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1534                                           SmallVectorImpl<uint64_t> &Record,
1535                                           unsigned &Abbrev) {
1536   if (!Abbrev)
1537     Abbrev = createDILocationAbbrev();
1538 
1539   Record.push_back(N->isDistinct());
1540   Record.push_back(N->getLine());
1541   Record.push_back(N->getColumn());
1542   Record.push_back(VE.getMetadataID(N->getScope()));
1543   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1544   Record.push_back(N->isImplicitCode());
1545 
1546   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1547   Record.clear();
1548 }
1549 
1550 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1551   // Assume the column is usually under 128, and always output the inlined-at
1552   // location (it's never more expensive than building an array size 1).
1553   auto Abbv = std::make_shared<BitCodeAbbrev>();
1554   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1555   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1556   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1557   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1558   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1559   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1560   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1561   return Stream.EmitAbbrev(std::move(Abbv));
1562 }
1563 
1564 void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1565                                              SmallVectorImpl<uint64_t> &Record,
1566                                              unsigned &Abbrev) {
1567   if (!Abbrev)
1568     Abbrev = createGenericDINodeAbbrev();
1569 
1570   Record.push_back(N->isDistinct());
1571   Record.push_back(N->getTag());
1572   Record.push_back(0); // Per-tag version field; unused for now.
1573 
1574   for (auto &I : N->operands())
1575     Record.push_back(VE.getMetadataOrNullID(I));
1576 
1577   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1578   Record.clear();
1579 }
1580 
1581 void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1582                                           SmallVectorImpl<uint64_t> &Record,
1583                                           unsigned Abbrev) {
1584   const uint64_t Version = 2 << 1;
1585   Record.push_back((uint64_t)N->isDistinct() | Version);
1586   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1587   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1588   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1589   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1590 
1591   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1592   Record.clear();
1593 }
1594 
1595 void ModuleBitcodeWriter::writeDIGenericSubrange(
1596     const DIGenericSubrange *N, SmallVectorImpl<uint64_t> &Record,
1597     unsigned Abbrev) {
1598   Record.push_back((uint64_t)N->isDistinct());
1599   Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1600   Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1601   Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1602   Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1603 
1604   Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1605   Record.clear();
1606 }
1607 
1608 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1609   if ((int64_t)V >= 0)
1610     Vals.push_back(V << 1);
1611   else
1612     Vals.push_back((-V << 1) | 1);
1613 }
1614 
1615 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
1616   // We have an arbitrary precision integer value to write whose
1617   // bit width is > 64. However, in canonical unsigned integer
1618   // format it is likely that the high bits are going to be zero.
1619   // So, we only write the number of active words.
1620   unsigned NumWords = A.getActiveWords();
1621   const uint64_t *RawData = A.getRawData();
1622   for (unsigned i = 0; i < NumWords; i++)
1623     emitSignedInt64(Vals, RawData[i]);
1624 }
1625 
1626 void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1627                                             SmallVectorImpl<uint64_t> &Record,
1628                                             unsigned Abbrev) {
1629   const uint64_t IsBigInt = 1 << 2;
1630   Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1631   Record.push_back(N->getValue().getBitWidth());
1632   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1633   emitWideAPInt(Record, N->getValue());
1634 
1635   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1636   Record.clear();
1637 }
1638 
1639 void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1640                                            SmallVectorImpl<uint64_t> &Record,
1641                                            unsigned Abbrev) {
1642   Record.push_back(N->isDistinct());
1643   Record.push_back(N->getTag());
1644   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1645   Record.push_back(N->getSizeInBits());
1646   Record.push_back(N->getAlignInBits());
1647   Record.push_back(N->getEncoding());
1648   Record.push_back(N->getFlags());
1649 
1650   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1651   Record.clear();
1652 }
1653 
1654 void ModuleBitcodeWriter::writeDIStringType(const DIStringType *N,
1655                                             SmallVectorImpl<uint64_t> &Record,
1656                                             unsigned Abbrev) {
1657   Record.push_back(N->isDistinct());
1658   Record.push_back(N->getTag());
1659   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1660   Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1661   Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1662   Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1663   Record.push_back(N->getSizeInBits());
1664   Record.push_back(N->getAlignInBits());
1665   Record.push_back(N->getEncoding());
1666 
1667   Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1668   Record.clear();
1669 }
1670 
1671 void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1672                                              SmallVectorImpl<uint64_t> &Record,
1673                                              unsigned Abbrev) {
1674   Record.push_back(N->isDistinct());
1675   Record.push_back(N->getTag());
1676   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1677   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1678   Record.push_back(N->getLine());
1679   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1680   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1681   Record.push_back(N->getSizeInBits());
1682   Record.push_back(N->getAlignInBits());
1683   Record.push_back(N->getOffsetInBits());
1684   Record.push_back(N->getFlags());
1685   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1686 
1687   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1688   // that there is no DWARF address space associated with DIDerivedType.
1689   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1690     Record.push_back(*DWARFAddressSpace + 1);
1691   else
1692     Record.push_back(0);
1693 
1694   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1695 
1696   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1697   Record.clear();
1698 }
1699 
1700 void ModuleBitcodeWriter::writeDICompositeType(
1701     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1702     unsigned Abbrev) {
1703   const unsigned IsNotUsedInOldTypeRef = 0x2;
1704   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1705   Record.push_back(N->getTag());
1706   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1707   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1708   Record.push_back(N->getLine());
1709   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1710   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1711   Record.push_back(N->getSizeInBits());
1712   Record.push_back(N->getAlignInBits());
1713   Record.push_back(N->getOffsetInBits());
1714   Record.push_back(N->getFlags());
1715   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1716   Record.push_back(N->getRuntimeLang());
1717   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1718   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1719   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1720   Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1721   Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1722   Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1723   Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1724   Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1725   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1726 
1727   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1728   Record.clear();
1729 }
1730 
1731 void ModuleBitcodeWriter::writeDISubroutineType(
1732     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1733     unsigned Abbrev) {
1734   const unsigned HasNoOldTypeRefs = 0x2;
1735   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1736   Record.push_back(N->getFlags());
1737   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1738   Record.push_back(N->getCC());
1739 
1740   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1741   Record.clear();
1742 }
1743 
1744 void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1745                                       SmallVectorImpl<uint64_t> &Record,
1746                                       unsigned Abbrev) {
1747   Record.push_back(N->isDistinct());
1748   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1749   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1750   if (N->getRawChecksum()) {
1751     Record.push_back(N->getRawChecksum()->Kind);
1752     Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1753   } else {
1754     // Maintain backwards compatibility with the old internal representation of
1755     // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1756     Record.push_back(0);
1757     Record.push_back(VE.getMetadataOrNullID(nullptr));
1758   }
1759   auto Source = N->getRawSource();
1760   if (Source)
1761     Record.push_back(VE.getMetadataOrNullID(*Source));
1762 
1763   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1764   Record.clear();
1765 }
1766 
1767 void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1768                                              SmallVectorImpl<uint64_t> &Record,
1769                                              unsigned Abbrev) {
1770   assert(N->isDistinct() && "Expected distinct compile units");
1771   Record.push_back(/* IsDistinct */ true);
1772   Record.push_back(N->getSourceLanguage());
1773   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1774   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1775   Record.push_back(N->isOptimized());
1776   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1777   Record.push_back(N->getRuntimeVersion());
1778   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1779   Record.push_back(N->getEmissionKind());
1780   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1781   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1782   Record.push_back(/* subprograms */ 0);
1783   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1784   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1785   Record.push_back(N->getDWOId());
1786   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1787   Record.push_back(N->getSplitDebugInlining());
1788   Record.push_back(N->getDebugInfoForProfiling());
1789   Record.push_back((unsigned)N->getNameTableKind());
1790   Record.push_back(N->getRangesBaseAddress());
1791   Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1792   Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1793 
1794   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1795   Record.clear();
1796 }
1797 
1798 void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1799                                             SmallVectorImpl<uint64_t> &Record,
1800                                             unsigned Abbrev) {
1801   const uint64_t HasUnitFlag = 1 << 1;
1802   const uint64_t HasSPFlagsFlag = 1 << 2;
1803   Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1804   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1805   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1806   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1807   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1808   Record.push_back(N->getLine());
1809   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1810   Record.push_back(N->getScopeLine());
1811   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1812   Record.push_back(N->getSPFlags());
1813   Record.push_back(N->getVirtualIndex());
1814   Record.push_back(N->getFlags());
1815   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1816   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1817   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1818   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1819   Record.push_back(N->getThisAdjustment());
1820   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1821   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1822 
1823   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1824   Record.clear();
1825 }
1826 
1827 void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1828                                               SmallVectorImpl<uint64_t> &Record,
1829                                               unsigned Abbrev) {
1830   Record.push_back(N->isDistinct());
1831   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1832   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1833   Record.push_back(N->getLine());
1834   Record.push_back(N->getColumn());
1835 
1836   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1837   Record.clear();
1838 }
1839 
1840 void ModuleBitcodeWriter::writeDILexicalBlockFile(
1841     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1842     unsigned Abbrev) {
1843   Record.push_back(N->isDistinct());
1844   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1845   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1846   Record.push_back(N->getDiscriminator());
1847 
1848   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1849   Record.clear();
1850 }
1851 
1852 void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
1853                                              SmallVectorImpl<uint64_t> &Record,
1854                                              unsigned Abbrev) {
1855   Record.push_back(N->isDistinct());
1856   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1857   Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1858   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1859   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1860   Record.push_back(N->getLineNo());
1861 
1862   Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
1863   Record.clear();
1864 }
1865 
1866 void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1867                                            SmallVectorImpl<uint64_t> &Record,
1868                                            unsigned Abbrev) {
1869   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1870   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1871   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1872 
1873   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1874   Record.clear();
1875 }
1876 
1877 void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1878                                        SmallVectorImpl<uint64_t> &Record,
1879                                        unsigned Abbrev) {
1880   Record.push_back(N->isDistinct());
1881   Record.push_back(N->getMacinfoType());
1882   Record.push_back(N->getLine());
1883   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1884   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1885 
1886   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1887   Record.clear();
1888 }
1889 
1890 void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1891                                            SmallVectorImpl<uint64_t> &Record,
1892                                            unsigned Abbrev) {
1893   Record.push_back(N->isDistinct());
1894   Record.push_back(N->getMacinfoType());
1895   Record.push_back(N->getLine());
1896   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1897   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1898 
1899   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1900   Record.clear();
1901 }
1902 
1903 void ModuleBitcodeWriter::writeDIArgList(const DIArgList *N,
1904                                          SmallVectorImpl<uint64_t> &Record,
1905                                          unsigned Abbrev) {
1906   Record.reserve(N->getArgs().size());
1907   for (ValueAsMetadata *MD : N->getArgs())
1908     Record.push_back(VE.getMetadataID(MD));
1909 
1910   Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);
1911   Record.clear();
1912 }
1913 
1914 void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1915                                         SmallVectorImpl<uint64_t> &Record,
1916                                         unsigned Abbrev) {
1917   Record.push_back(N->isDistinct());
1918   for (auto &I : N->operands())
1919     Record.push_back(VE.getMetadataOrNullID(I));
1920   Record.push_back(N->getLineNo());
1921   Record.push_back(N->getIsDecl());
1922 
1923   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1924   Record.clear();
1925 }
1926 
1927 void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1928     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1929     unsigned Abbrev) {
1930   Record.push_back(N->isDistinct());
1931   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1932   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1933   Record.push_back(N->isDefault());
1934 
1935   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1936   Record.clear();
1937 }
1938 
1939 void ModuleBitcodeWriter::writeDITemplateValueParameter(
1940     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1941     unsigned Abbrev) {
1942   Record.push_back(N->isDistinct());
1943   Record.push_back(N->getTag());
1944   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1945   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1946   Record.push_back(N->isDefault());
1947   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1948 
1949   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1950   Record.clear();
1951 }
1952 
1953 void ModuleBitcodeWriter::writeDIGlobalVariable(
1954     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1955     unsigned Abbrev) {
1956   const uint64_t Version = 2 << 1;
1957   Record.push_back((uint64_t)N->isDistinct() | Version);
1958   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1959   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1960   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1961   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1962   Record.push_back(N->getLine());
1963   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1964   Record.push_back(N->isLocalToUnit());
1965   Record.push_back(N->isDefinition());
1966   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1967   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1968   Record.push_back(N->getAlignInBits());
1969   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1970 
1971   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1972   Record.clear();
1973 }
1974 
1975 void ModuleBitcodeWriter::writeDILocalVariable(
1976     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1977     unsigned Abbrev) {
1978   // In order to support all possible bitcode formats in BitcodeReader we need
1979   // to distinguish the following cases:
1980   // 1) Record has no artificial tag (Record[1]),
1981   //   has no obsolete inlinedAt field (Record[9]).
1982   //   In this case Record size will be 8, HasAlignment flag is false.
1983   // 2) Record has artificial tag (Record[1]),
1984   //   has no obsolete inlignedAt field (Record[9]).
1985   //   In this case Record size will be 9, HasAlignment flag is false.
1986   // 3) Record has both artificial tag (Record[1]) and
1987   //   obsolete inlignedAt field (Record[9]).
1988   //   In this case Record size will be 10, HasAlignment flag is false.
1989   // 4) Record has neither artificial tag, nor inlignedAt field, but
1990   //   HasAlignment flag is true and Record[8] contains alignment value.
1991   const uint64_t HasAlignmentFlag = 1 << 1;
1992   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1993   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1994   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1995   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1996   Record.push_back(N->getLine());
1997   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1998   Record.push_back(N->getArg());
1999   Record.push_back(N->getFlags());
2000   Record.push_back(N->getAlignInBits());
2001   Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2002 
2003   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2004   Record.clear();
2005 }
2006 
2007 void ModuleBitcodeWriter::writeDILabel(
2008     const DILabel *N, SmallVectorImpl<uint64_t> &Record,
2009     unsigned Abbrev) {
2010   Record.push_back((uint64_t)N->isDistinct());
2011   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2012   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2013   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2014   Record.push_back(N->getLine());
2015 
2016   Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2017   Record.clear();
2018 }
2019 
2020 void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
2021                                             SmallVectorImpl<uint64_t> &Record,
2022                                             unsigned Abbrev) {
2023   Record.reserve(N->getElements().size() + 1);
2024   const uint64_t Version = 3 << 1;
2025   Record.push_back((uint64_t)N->isDistinct() | Version);
2026   Record.append(N->elements_begin(), N->elements_end());
2027 
2028   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2029   Record.clear();
2030 }
2031 
2032 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2033     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
2034     unsigned Abbrev) {
2035   Record.push_back(N->isDistinct());
2036   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2037   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2038 
2039   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2040   Record.clear();
2041 }
2042 
2043 void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
2044                                               SmallVectorImpl<uint64_t> &Record,
2045                                               unsigned Abbrev) {
2046   Record.push_back(N->isDistinct());
2047   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2048   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2049   Record.push_back(N->getLine());
2050   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2051   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2052   Record.push_back(N->getAttributes());
2053   Record.push_back(VE.getMetadataOrNullID(N->getType()));
2054 
2055   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2056   Record.clear();
2057 }
2058 
2059 void ModuleBitcodeWriter::writeDIImportedEntity(
2060     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
2061     unsigned Abbrev) {
2062   Record.push_back(N->isDistinct());
2063   Record.push_back(N->getTag());
2064   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2065   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2066   Record.push_back(N->getLine());
2067   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2068   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2069   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2070 
2071   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2072   Record.clear();
2073 }
2074 
2075 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2076   auto Abbv = std::make_shared<BitCodeAbbrev>();
2077   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
2078   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2079   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2080   return Stream.EmitAbbrev(std::move(Abbv));
2081 }
2082 
2083 void ModuleBitcodeWriter::writeNamedMetadata(
2084     SmallVectorImpl<uint64_t> &Record) {
2085   if (M.named_metadata_empty())
2086     return;
2087 
2088   unsigned Abbrev = createNamedMetadataAbbrev();
2089   for (const NamedMDNode &NMD : M.named_metadata()) {
2090     // Write name.
2091     StringRef Str = NMD.getName();
2092     Record.append(Str.bytes_begin(), Str.bytes_end());
2093     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2094     Record.clear();
2095 
2096     // Write named metadata operands.
2097     for (const MDNode *N : NMD.operands())
2098       Record.push_back(VE.getMetadataID(N));
2099     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2100     Record.clear();
2101   }
2102 }
2103 
2104 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2105   auto Abbv = std::make_shared<BitCodeAbbrev>();
2106   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
2107   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2108   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2109   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2110   return Stream.EmitAbbrev(std::move(Abbv));
2111 }
2112 
2113 /// Write out a record for MDString.
2114 ///
2115 /// All the metadata strings in a metadata block are emitted in a single
2116 /// record.  The sizes and strings themselves are shoved into a blob.
2117 void ModuleBitcodeWriter::writeMetadataStrings(
2118     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
2119   if (Strings.empty())
2120     return;
2121 
2122   // Start the record with the number of strings.
2123   Record.push_back(bitc::METADATA_STRINGS);
2124   Record.push_back(Strings.size());
2125 
2126   // Emit the sizes of the strings in the blob.
2127   SmallString<256> Blob;
2128   {
2129     BitstreamWriter W(Blob);
2130     for (const Metadata *MD : Strings)
2131       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2132     W.FlushToWord();
2133   }
2134 
2135   // Add the offset to the strings to the record.
2136   Record.push_back(Blob.size());
2137 
2138   // Add the strings to the blob.
2139   for (const Metadata *MD : Strings)
2140     Blob.append(cast<MDString>(MD)->getString());
2141 
2142   // Emit the final record.
2143   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2144   Record.clear();
2145 }
2146 
2147 // Generates an enum to use as an index in the Abbrev array of Metadata record.
2148 enum MetadataAbbrev : unsigned {
2149 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2150 #include "llvm/IR/Metadata.def"
2151   LastPlusOne
2152 };
2153 
2154 void ModuleBitcodeWriter::writeMetadataRecords(
2155     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
2156     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2157   if (MDs.empty())
2158     return;
2159 
2160   // Initialize MDNode abbreviations.
2161 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2162 #include "llvm/IR/Metadata.def"
2163 
2164   for (const Metadata *MD : MDs) {
2165     if (IndexPos)
2166       IndexPos->push_back(Stream.GetCurrentBitNo());
2167     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2168       assert(N->isResolved() && "Expected forward references to be resolved");
2169 
2170       switch (N->getMetadataID()) {
2171       default:
2172         llvm_unreachable("Invalid MDNode subclass");
2173 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
2174   case Metadata::CLASS##Kind:                                                  \
2175     if (MDAbbrevs)                                                             \
2176       write##CLASS(cast<CLASS>(N), Record,                                     \
2177                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
2178     else                                                                       \
2179       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
2180     continue;
2181 #include "llvm/IR/Metadata.def"
2182       }
2183     }
2184     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2185   }
2186 }
2187 
2188 void ModuleBitcodeWriter::writeModuleMetadata() {
2189   if (!VE.hasMDs() && M.named_metadata_empty())
2190     return;
2191 
2192   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
2193   SmallVector<uint64_t, 64> Record;
2194 
2195   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2196   // block and load any metadata.
2197   std::vector<unsigned> MDAbbrevs;
2198 
2199   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2200   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2201   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2202       createGenericDINodeAbbrev();
2203 
2204   auto Abbv = std::make_shared<BitCodeAbbrev>();
2205   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
2206   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2207   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2208   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2209 
2210   Abbv = std::make_shared<BitCodeAbbrev>();
2211   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2212   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2213   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2214   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2215 
2216   // Emit MDStrings together upfront.
2217   writeMetadataStrings(VE.getMDStrings(), Record);
2218 
2219   // We only emit an index for the metadata record if we have more than a given
2220   // (naive) threshold of metadatas, otherwise it is not worth it.
2221   if (VE.getNonMDStrings().size() > IndexThreshold) {
2222     // Write a placeholder value in for the offset of the metadata index,
2223     // which is written after the records, so that it can include
2224     // the offset of each entry. The placeholder offset will be
2225     // updated after all records are emitted.
2226     uint64_t Vals[] = {0, 0};
2227     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2228   }
2229 
2230   // Compute and save the bit offset to the current position, which will be
2231   // patched when we emit the index later. We can simply subtract the 64-bit
2232   // fixed size from the current bit number to get the location to backpatch.
2233   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2234 
2235   // This index will contain the bitpos for each individual record.
2236   std::vector<uint64_t> IndexPos;
2237   IndexPos.reserve(VE.getNonMDStrings().size());
2238 
2239   // Write all the records
2240   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2241 
2242   if (VE.getNonMDStrings().size() > IndexThreshold) {
2243     // Now that we have emitted all the records we will emit the index. But
2244     // first
2245     // backpatch the forward reference so that the reader can skip the records
2246     // efficiently.
2247     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2248                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2249 
2250     // Delta encode the index.
2251     uint64_t PreviousValue = IndexOffsetRecordBitPos;
2252     for (auto &Elt : IndexPos) {
2253       auto EltDelta = Elt - PreviousValue;
2254       PreviousValue = Elt;
2255       Elt = EltDelta;
2256     }
2257     // Emit the index record.
2258     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2259     IndexPos.clear();
2260   }
2261 
2262   // Write the named metadata now.
2263   writeNamedMetadata(Record);
2264 
2265   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2266     SmallVector<uint64_t, 4> Record;
2267     Record.push_back(VE.getValueID(&GO));
2268     pushGlobalMetadataAttachment(Record, GO);
2269     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2270   };
2271   for (const Function &F : M)
2272     if (F.isDeclaration() && F.hasMetadata())
2273       AddDeclAttachedMetadata(F);
2274   // FIXME: Only store metadata for declarations here, and move data for global
2275   // variable definitions to a separate block (PR28134).
2276   for (const GlobalVariable &GV : M.globals())
2277     if (GV.hasMetadata())
2278       AddDeclAttachedMetadata(GV);
2279 
2280   Stream.ExitBlock();
2281 }
2282 
2283 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2284   if (!VE.hasMDs())
2285     return;
2286 
2287   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2288   SmallVector<uint64_t, 64> Record;
2289   writeMetadataStrings(VE.getMDStrings(), Record);
2290   writeMetadataRecords(VE.getNonMDStrings(), Record);
2291   Stream.ExitBlock();
2292 }
2293 
2294 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2295     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2296   // [n x [id, mdnode]]
2297   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2298   GO.getAllMetadata(MDs);
2299   for (const auto &I : MDs) {
2300     Record.push_back(I.first);
2301     Record.push_back(VE.getMetadataID(I.second));
2302   }
2303 }
2304 
2305 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2306   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2307 
2308   SmallVector<uint64_t, 64> Record;
2309 
2310   if (F.hasMetadata()) {
2311     pushGlobalMetadataAttachment(Record, F);
2312     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2313     Record.clear();
2314   }
2315 
2316   // Write metadata attachments
2317   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2318   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2319   for (const BasicBlock &BB : F)
2320     for (const Instruction &I : BB) {
2321       MDs.clear();
2322       I.getAllMetadataOtherThanDebugLoc(MDs);
2323 
2324       // If no metadata, ignore instruction.
2325       if (MDs.empty()) continue;
2326 
2327       Record.push_back(VE.getInstructionID(&I));
2328 
2329       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2330         Record.push_back(MDs[i].first);
2331         Record.push_back(VE.getMetadataID(MDs[i].second));
2332       }
2333       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2334       Record.clear();
2335     }
2336 
2337   Stream.ExitBlock();
2338 }
2339 
2340 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2341   SmallVector<uint64_t, 64> Record;
2342 
2343   // Write metadata kinds
2344   // METADATA_KIND - [n x [id, name]]
2345   SmallVector<StringRef, 8> Names;
2346   M.getMDKindNames(Names);
2347 
2348   if (Names.empty()) return;
2349 
2350   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2351 
2352   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2353     Record.push_back(MDKindID);
2354     StringRef KName = Names[MDKindID];
2355     Record.append(KName.begin(), KName.end());
2356 
2357     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2358     Record.clear();
2359   }
2360 
2361   Stream.ExitBlock();
2362 }
2363 
2364 void ModuleBitcodeWriter::writeOperandBundleTags() {
2365   // Write metadata kinds
2366   //
2367   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2368   //
2369   // OPERAND_BUNDLE_TAG - [strchr x N]
2370 
2371   SmallVector<StringRef, 8> Tags;
2372   M.getOperandBundleTags(Tags);
2373 
2374   if (Tags.empty())
2375     return;
2376 
2377   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2378 
2379   SmallVector<uint64_t, 64> Record;
2380 
2381   for (auto Tag : Tags) {
2382     Record.append(Tag.begin(), Tag.end());
2383 
2384     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2385     Record.clear();
2386   }
2387 
2388   Stream.ExitBlock();
2389 }
2390 
2391 void ModuleBitcodeWriter::writeSyncScopeNames() {
2392   SmallVector<StringRef, 8> SSNs;
2393   M.getContext().getSyncScopeNames(SSNs);
2394   if (SSNs.empty())
2395     return;
2396 
2397   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2398 
2399   SmallVector<uint64_t, 64> Record;
2400   for (auto SSN : SSNs) {
2401     Record.append(SSN.begin(), SSN.end());
2402     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2403     Record.clear();
2404   }
2405 
2406   Stream.ExitBlock();
2407 }
2408 
2409 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2410                                          bool isGlobal) {
2411   if (FirstVal == LastVal) return;
2412 
2413   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2414 
2415   unsigned AggregateAbbrev = 0;
2416   unsigned String8Abbrev = 0;
2417   unsigned CString7Abbrev = 0;
2418   unsigned CString6Abbrev = 0;
2419   // If this is a constant pool for the module, emit module-specific abbrevs.
2420   if (isGlobal) {
2421     // Abbrev for CST_CODE_AGGREGATE.
2422     auto Abbv = std::make_shared<BitCodeAbbrev>();
2423     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2424     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2425     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2426     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2427 
2428     // Abbrev for CST_CODE_STRING.
2429     Abbv = std::make_shared<BitCodeAbbrev>();
2430     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2431     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2432     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2433     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2434     // Abbrev for CST_CODE_CSTRING.
2435     Abbv = std::make_shared<BitCodeAbbrev>();
2436     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2437     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2438     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2439     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2440     // Abbrev for CST_CODE_CSTRING.
2441     Abbv = std::make_shared<BitCodeAbbrev>();
2442     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2443     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2444     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2445     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2446   }
2447 
2448   SmallVector<uint64_t, 64> Record;
2449 
2450   const ValueEnumerator::ValueList &Vals = VE.getValues();
2451   Type *LastTy = nullptr;
2452   for (unsigned i = FirstVal; i != LastVal; ++i) {
2453     const Value *V = Vals[i].first;
2454     // If we need to switch types, do so now.
2455     if (V->getType() != LastTy) {
2456       LastTy = V->getType();
2457       Record.push_back(VE.getTypeID(LastTy));
2458       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2459                         CONSTANTS_SETTYPE_ABBREV);
2460       Record.clear();
2461     }
2462 
2463     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2464       Record.push_back(VE.getTypeID(IA->getFunctionType()));
2465       Record.push_back(
2466           unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2467           unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2468 
2469       // Add the asm string.
2470       const std::string &AsmStr = IA->getAsmString();
2471       Record.push_back(AsmStr.size());
2472       Record.append(AsmStr.begin(), AsmStr.end());
2473 
2474       // Add the constraint string.
2475       const std::string &ConstraintStr = IA->getConstraintString();
2476       Record.push_back(ConstraintStr.size());
2477       Record.append(ConstraintStr.begin(), ConstraintStr.end());
2478       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2479       Record.clear();
2480       continue;
2481     }
2482     const Constant *C = cast<Constant>(V);
2483     unsigned Code = -1U;
2484     unsigned AbbrevToUse = 0;
2485     if (C->isNullValue()) {
2486       Code = bitc::CST_CODE_NULL;
2487     } else if (isa<PoisonValue>(C)) {
2488       Code = bitc::CST_CODE_POISON;
2489     } else if (isa<UndefValue>(C)) {
2490       Code = bitc::CST_CODE_UNDEF;
2491     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2492       if (IV->getBitWidth() <= 64) {
2493         uint64_t V = IV->getSExtValue();
2494         emitSignedInt64(Record, V);
2495         Code = bitc::CST_CODE_INTEGER;
2496         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2497       } else {                             // Wide integers, > 64 bits in size.
2498         emitWideAPInt(Record, IV->getValue());
2499         Code = bitc::CST_CODE_WIDE_INTEGER;
2500       }
2501     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2502       Code = bitc::CST_CODE_FLOAT;
2503       Type *Ty = CFP->getType();
2504       if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2505           Ty->isDoubleTy()) {
2506         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2507       } else if (Ty->isX86_FP80Ty()) {
2508         // api needed to prevent premature destruction
2509         // bits are not in the same order as a normal i80 APInt, compensate.
2510         APInt api = CFP->getValueAPF().bitcastToAPInt();
2511         const uint64_t *p = api.getRawData();
2512         Record.push_back((p[1] << 48) | (p[0] >> 16));
2513         Record.push_back(p[0] & 0xffffLL);
2514       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2515         APInt api = CFP->getValueAPF().bitcastToAPInt();
2516         const uint64_t *p = api.getRawData();
2517         Record.push_back(p[0]);
2518         Record.push_back(p[1]);
2519       } else {
2520         assert(0 && "Unknown FP type!");
2521       }
2522     } else if (isa<ConstantDataSequential>(C) &&
2523                cast<ConstantDataSequential>(C)->isString()) {
2524       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2525       // Emit constant strings specially.
2526       unsigned NumElts = Str->getNumElements();
2527       // If this is a null-terminated string, use the denser CSTRING encoding.
2528       if (Str->isCString()) {
2529         Code = bitc::CST_CODE_CSTRING;
2530         --NumElts;  // Don't encode the null, which isn't allowed by char6.
2531       } else {
2532         Code = bitc::CST_CODE_STRING;
2533         AbbrevToUse = String8Abbrev;
2534       }
2535       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2536       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2537       for (unsigned i = 0; i != NumElts; ++i) {
2538         unsigned char V = Str->getElementAsInteger(i);
2539         Record.push_back(V);
2540         isCStr7 &= (V & 128) == 0;
2541         if (isCStrChar6)
2542           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2543       }
2544 
2545       if (isCStrChar6)
2546         AbbrevToUse = CString6Abbrev;
2547       else if (isCStr7)
2548         AbbrevToUse = CString7Abbrev;
2549     } else if (const ConstantDataSequential *CDS =
2550                   dyn_cast<ConstantDataSequential>(C)) {
2551       Code = bitc::CST_CODE_DATA;
2552       Type *EltTy = CDS->getElementType();
2553       if (isa<IntegerType>(EltTy)) {
2554         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2555           Record.push_back(CDS->getElementAsInteger(i));
2556       } else {
2557         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2558           Record.push_back(
2559               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2560       }
2561     } else if (isa<ConstantAggregate>(C)) {
2562       Code = bitc::CST_CODE_AGGREGATE;
2563       for (const Value *Op : C->operands())
2564         Record.push_back(VE.getValueID(Op));
2565       AbbrevToUse = AggregateAbbrev;
2566     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2567       switch (CE->getOpcode()) {
2568       default:
2569         if (Instruction::isCast(CE->getOpcode())) {
2570           Code = bitc::CST_CODE_CE_CAST;
2571           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2572           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2573           Record.push_back(VE.getValueID(C->getOperand(0)));
2574           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2575         } else {
2576           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2577           Code = bitc::CST_CODE_CE_BINOP;
2578           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2579           Record.push_back(VE.getValueID(C->getOperand(0)));
2580           Record.push_back(VE.getValueID(C->getOperand(1)));
2581           uint64_t Flags = getOptimizationFlags(CE);
2582           if (Flags != 0)
2583             Record.push_back(Flags);
2584         }
2585         break;
2586       case Instruction::FNeg: {
2587         assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2588         Code = bitc::CST_CODE_CE_UNOP;
2589         Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2590         Record.push_back(VE.getValueID(C->getOperand(0)));
2591         uint64_t Flags = getOptimizationFlags(CE);
2592         if (Flags != 0)
2593           Record.push_back(Flags);
2594         break;
2595       }
2596       case Instruction::GetElementPtr: {
2597         Code = bitc::CST_CODE_CE_GEP;
2598         const auto *GO = cast<GEPOperator>(C);
2599         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2600         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2601           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2602           Record.push_back((*Idx << 1) | GO->isInBounds());
2603         } else if (GO->isInBounds())
2604           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2605         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2606           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2607           Record.push_back(VE.getValueID(C->getOperand(i)));
2608         }
2609         break;
2610       }
2611       case Instruction::Select:
2612         Code = bitc::CST_CODE_CE_SELECT;
2613         Record.push_back(VE.getValueID(C->getOperand(0)));
2614         Record.push_back(VE.getValueID(C->getOperand(1)));
2615         Record.push_back(VE.getValueID(C->getOperand(2)));
2616         break;
2617       case Instruction::ExtractElement:
2618         Code = bitc::CST_CODE_CE_EXTRACTELT;
2619         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2620         Record.push_back(VE.getValueID(C->getOperand(0)));
2621         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2622         Record.push_back(VE.getValueID(C->getOperand(1)));
2623         break;
2624       case Instruction::InsertElement:
2625         Code = bitc::CST_CODE_CE_INSERTELT;
2626         Record.push_back(VE.getValueID(C->getOperand(0)));
2627         Record.push_back(VE.getValueID(C->getOperand(1)));
2628         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2629         Record.push_back(VE.getValueID(C->getOperand(2)));
2630         break;
2631       case Instruction::ShuffleVector:
2632         // If the return type and argument types are the same, this is a
2633         // standard shufflevector instruction.  If the types are different,
2634         // then the shuffle is widening or truncating the input vectors, and
2635         // the argument type must also be encoded.
2636         if (C->getType() == C->getOperand(0)->getType()) {
2637           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2638         } else {
2639           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2640           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2641         }
2642         Record.push_back(VE.getValueID(C->getOperand(0)));
2643         Record.push_back(VE.getValueID(C->getOperand(1)));
2644         Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2645         break;
2646       case Instruction::ICmp:
2647       case Instruction::FCmp:
2648         Code = bitc::CST_CODE_CE_CMP;
2649         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2650         Record.push_back(VE.getValueID(C->getOperand(0)));
2651         Record.push_back(VE.getValueID(C->getOperand(1)));
2652         Record.push_back(CE->getPredicate());
2653         break;
2654       }
2655     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2656       Code = bitc::CST_CODE_BLOCKADDRESS;
2657       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2658       Record.push_back(VE.getValueID(BA->getFunction()));
2659       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2660     } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2661       Code = bitc::CST_CODE_DSO_LOCAL_EQUIVALENT;
2662       Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2663       Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2664     } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2665       Code = bitc::CST_CODE_NO_CFI_VALUE;
2666       Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2667       Record.push_back(VE.getValueID(NC->getGlobalValue()));
2668     } else {
2669 #ifndef NDEBUG
2670       C->dump();
2671 #endif
2672       llvm_unreachable("Unknown constant!");
2673     }
2674     Stream.EmitRecord(Code, Record, AbbrevToUse);
2675     Record.clear();
2676   }
2677 
2678   Stream.ExitBlock();
2679 }
2680 
2681 void ModuleBitcodeWriter::writeModuleConstants() {
2682   const ValueEnumerator::ValueList &Vals = VE.getValues();
2683 
2684   // Find the first constant to emit, which is the first non-globalvalue value.
2685   // We know globalvalues have been emitted by WriteModuleInfo.
2686   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2687     if (!isa<GlobalValue>(Vals[i].first)) {
2688       writeConstants(i, Vals.size(), true);
2689       return;
2690     }
2691   }
2692 }
2693 
2694 /// pushValueAndType - The file has to encode both the value and type id for
2695 /// many values, because we need to know what type to create for forward
2696 /// references.  However, most operands are not forward references, so this type
2697 /// field is not needed.
2698 ///
2699 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2700 /// instruction ID, then it is a forward reference, and it also includes the
2701 /// type ID.  The value ID that is written is encoded relative to the InstID.
2702 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2703                                            SmallVectorImpl<unsigned> &Vals) {
2704   unsigned ValID = VE.getValueID(V);
2705   // Make encoding relative to the InstID.
2706   Vals.push_back(InstID - ValID);
2707   if (ValID >= InstID) {
2708     Vals.push_back(VE.getTypeID(V->getType()));
2709     return true;
2710   }
2711   return false;
2712 }
2713 
2714 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2715                                               unsigned InstID) {
2716   SmallVector<unsigned, 64> Record;
2717   LLVMContext &C = CS.getContext();
2718 
2719   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2720     const auto &Bundle = CS.getOperandBundleAt(i);
2721     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2722 
2723     for (auto &Input : Bundle.Inputs)
2724       pushValueAndType(Input, InstID, Record);
2725 
2726     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2727     Record.clear();
2728   }
2729 }
2730 
2731 /// pushValue - Like pushValueAndType, but where the type of the value is
2732 /// omitted (perhaps it was already encoded in an earlier operand).
2733 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2734                                     SmallVectorImpl<unsigned> &Vals) {
2735   unsigned ValID = VE.getValueID(V);
2736   Vals.push_back(InstID - ValID);
2737 }
2738 
2739 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2740                                           SmallVectorImpl<uint64_t> &Vals) {
2741   unsigned ValID = VE.getValueID(V);
2742   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2743   emitSignedInt64(Vals, diff);
2744 }
2745 
2746 /// WriteInstruction - Emit an instruction to the specified stream.
2747 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2748                                            unsigned InstID,
2749                                            SmallVectorImpl<unsigned> &Vals) {
2750   unsigned Code = 0;
2751   unsigned AbbrevToUse = 0;
2752   VE.setInstructionID(&I);
2753   switch (I.getOpcode()) {
2754   default:
2755     if (Instruction::isCast(I.getOpcode())) {
2756       Code = bitc::FUNC_CODE_INST_CAST;
2757       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2758         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2759       Vals.push_back(VE.getTypeID(I.getType()));
2760       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2761     } else {
2762       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2763       Code = bitc::FUNC_CODE_INST_BINOP;
2764       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2765         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2766       pushValue(I.getOperand(1), InstID, Vals);
2767       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2768       uint64_t Flags = getOptimizationFlags(&I);
2769       if (Flags != 0) {
2770         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2771           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2772         Vals.push_back(Flags);
2773       }
2774     }
2775     break;
2776   case Instruction::FNeg: {
2777     Code = bitc::FUNC_CODE_INST_UNOP;
2778     if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2779       AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2780     Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2781     uint64_t Flags = getOptimizationFlags(&I);
2782     if (Flags != 0) {
2783       if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2784         AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2785       Vals.push_back(Flags);
2786     }
2787     break;
2788   }
2789   case Instruction::GetElementPtr: {
2790     Code = bitc::FUNC_CODE_INST_GEP;
2791     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2792     auto &GEPInst = cast<GetElementPtrInst>(I);
2793     Vals.push_back(GEPInst.isInBounds());
2794     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2795     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2796       pushValueAndType(I.getOperand(i), InstID, Vals);
2797     break;
2798   }
2799   case Instruction::ExtractValue: {
2800     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2801     pushValueAndType(I.getOperand(0), InstID, Vals);
2802     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2803     Vals.append(EVI->idx_begin(), EVI->idx_end());
2804     break;
2805   }
2806   case Instruction::InsertValue: {
2807     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2808     pushValueAndType(I.getOperand(0), InstID, Vals);
2809     pushValueAndType(I.getOperand(1), InstID, Vals);
2810     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2811     Vals.append(IVI->idx_begin(), IVI->idx_end());
2812     break;
2813   }
2814   case Instruction::Select: {
2815     Code = bitc::FUNC_CODE_INST_VSELECT;
2816     pushValueAndType(I.getOperand(1), InstID, Vals);
2817     pushValue(I.getOperand(2), InstID, Vals);
2818     pushValueAndType(I.getOperand(0), InstID, Vals);
2819     uint64_t Flags = getOptimizationFlags(&I);
2820     if (Flags != 0)
2821       Vals.push_back(Flags);
2822     break;
2823   }
2824   case Instruction::ExtractElement:
2825     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2826     pushValueAndType(I.getOperand(0), InstID, Vals);
2827     pushValueAndType(I.getOperand(1), InstID, Vals);
2828     break;
2829   case Instruction::InsertElement:
2830     Code = bitc::FUNC_CODE_INST_INSERTELT;
2831     pushValueAndType(I.getOperand(0), InstID, Vals);
2832     pushValue(I.getOperand(1), InstID, Vals);
2833     pushValueAndType(I.getOperand(2), InstID, Vals);
2834     break;
2835   case Instruction::ShuffleVector:
2836     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2837     pushValueAndType(I.getOperand(0), InstID, Vals);
2838     pushValue(I.getOperand(1), InstID, Vals);
2839     pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2840               Vals);
2841     break;
2842   case Instruction::ICmp:
2843   case Instruction::FCmp: {
2844     // compare returning Int1Ty or vector of Int1Ty
2845     Code = bitc::FUNC_CODE_INST_CMP2;
2846     pushValueAndType(I.getOperand(0), InstID, Vals);
2847     pushValue(I.getOperand(1), InstID, Vals);
2848     Vals.push_back(cast<CmpInst>(I).getPredicate());
2849     uint64_t Flags = getOptimizationFlags(&I);
2850     if (Flags != 0)
2851       Vals.push_back(Flags);
2852     break;
2853   }
2854 
2855   case Instruction::Ret:
2856     {
2857       Code = bitc::FUNC_CODE_INST_RET;
2858       unsigned NumOperands = I.getNumOperands();
2859       if (NumOperands == 0)
2860         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2861       else if (NumOperands == 1) {
2862         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2863           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2864       } else {
2865         for (unsigned i = 0, e = NumOperands; i != e; ++i)
2866           pushValueAndType(I.getOperand(i), InstID, Vals);
2867       }
2868     }
2869     break;
2870   case Instruction::Br:
2871     {
2872       Code = bitc::FUNC_CODE_INST_BR;
2873       const BranchInst &II = cast<BranchInst>(I);
2874       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2875       if (II.isConditional()) {
2876         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2877         pushValue(II.getCondition(), InstID, Vals);
2878       }
2879     }
2880     break;
2881   case Instruction::Switch:
2882     {
2883       Code = bitc::FUNC_CODE_INST_SWITCH;
2884       const SwitchInst &SI = cast<SwitchInst>(I);
2885       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2886       pushValue(SI.getCondition(), InstID, Vals);
2887       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2888       for (auto Case : SI.cases()) {
2889         Vals.push_back(VE.getValueID(Case.getCaseValue()));
2890         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2891       }
2892     }
2893     break;
2894   case Instruction::IndirectBr:
2895     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2896     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2897     // Encode the address operand as relative, but not the basic blocks.
2898     pushValue(I.getOperand(0), InstID, Vals);
2899     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2900       Vals.push_back(VE.getValueID(I.getOperand(i)));
2901     break;
2902 
2903   case Instruction::Invoke: {
2904     const InvokeInst *II = cast<InvokeInst>(&I);
2905     const Value *Callee = II->getCalledOperand();
2906     FunctionType *FTy = II->getFunctionType();
2907 
2908     if (II->hasOperandBundles())
2909       writeOperandBundles(*II, InstID);
2910 
2911     Code = bitc::FUNC_CODE_INST_INVOKE;
2912 
2913     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2914     Vals.push_back(II->getCallingConv() | 1 << 13);
2915     Vals.push_back(VE.getValueID(II->getNormalDest()));
2916     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2917     Vals.push_back(VE.getTypeID(FTy));
2918     pushValueAndType(Callee, InstID, Vals);
2919 
2920     // Emit value #'s for the fixed parameters.
2921     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2922       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2923 
2924     // Emit type/value pairs for varargs params.
2925     if (FTy->isVarArg()) {
2926       for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
2927         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2928     }
2929     break;
2930   }
2931   case Instruction::Resume:
2932     Code = bitc::FUNC_CODE_INST_RESUME;
2933     pushValueAndType(I.getOperand(0), InstID, Vals);
2934     break;
2935   case Instruction::CleanupRet: {
2936     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2937     const auto &CRI = cast<CleanupReturnInst>(I);
2938     pushValue(CRI.getCleanupPad(), InstID, Vals);
2939     if (CRI.hasUnwindDest())
2940       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2941     break;
2942   }
2943   case Instruction::CatchRet: {
2944     Code = bitc::FUNC_CODE_INST_CATCHRET;
2945     const auto &CRI = cast<CatchReturnInst>(I);
2946     pushValue(CRI.getCatchPad(), InstID, Vals);
2947     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2948     break;
2949   }
2950   case Instruction::CleanupPad:
2951   case Instruction::CatchPad: {
2952     const auto &FuncletPad = cast<FuncletPadInst>(I);
2953     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2954                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
2955     pushValue(FuncletPad.getParentPad(), InstID, Vals);
2956 
2957     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2958     Vals.push_back(NumArgOperands);
2959     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2960       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2961     break;
2962   }
2963   case Instruction::CatchSwitch: {
2964     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2965     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2966 
2967     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2968 
2969     unsigned NumHandlers = CatchSwitch.getNumHandlers();
2970     Vals.push_back(NumHandlers);
2971     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2972       Vals.push_back(VE.getValueID(CatchPadBB));
2973 
2974     if (CatchSwitch.hasUnwindDest())
2975       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2976     break;
2977   }
2978   case Instruction::CallBr: {
2979     const CallBrInst *CBI = cast<CallBrInst>(&I);
2980     const Value *Callee = CBI->getCalledOperand();
2981     FunctionType *FTy = CBI->getFunctionType();
2982 
2983     if (CBI->hasOperandBundles())
2984       writeOperandBundles(*CBI, InstID);
2985 
2986     Code = bitc::FUNC_CODE_INST_CALLBR;
2987 
2988     Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
2989 
2990     Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
2991                    1 << bitc::CALL_EXPLICIT_TYPE);
2992 
2993     Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
2994     Vals.push_back(CBI->getNumIndirectDests());
2995     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
2996       Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
2997 
2998     Vals.push_back(VE.getTypeID(FTy));
2999     pushValueAndType(Callee, InstID, Vals);
3000 
3001     // Emit value #'s for the fixed parameters.
3002     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3003       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3004 
3005     // Emit type/value pairs for varargs params.
3006     if (FTy->isVarArg()) {
3007       for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3008         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3009     }
3010     break;
3011   }
3012   case Instruction::Unreachable:
3013     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
3014     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3015     break;
3016 
3017   case Instruction::PHI: {
3018     const PHINode &PN = cast<PHINode>(I);
3019     Code = bitc::FUNC_CODE_INST_PHI;
3020     // With the newer instruction encoding, forward references could give
3021     // negative valued IDs.  This is most common for PHIs, so we use
3022     // signed VBRs.
3023     SmallVector<uint64_t, 128> Vals64;
3024     Vals64.push_back(VE.getTypeID(PN.getType()));
3025     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3026       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3027       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3028     }
3029 
3030     uint64_t Flags = getOptimizationFlags(&I);
3031     if (Flags != 0)
3032       Vals64.push_back(Flags);
3033 
3034     // Emit a Vals64 vector and exit.
3035     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3036     Vals64.clear();
3037     return;
3038   }
3039 
3040   case Instruction::LandingPad: {
3041     const LandingPadInst &LP = cast<LandingPadInst>(I);
3042     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
3043     Vals.push_back(VE.getTypeID(LP.getType()));
3044     Vals.push_back(LP.isCleanup());
3045     Vals.push_back(LP.getNumClauses());
3046     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3047       if (LP.isCatch(I))
3048         Vals.push_back(LandingPadInst::Catch);
3049       else
3050         Vals.push_back(LandingPadInst::Filter);
3051       pushValueAndType(LP.getClause(I), InstID, Vals);
3052     }
3053     break;
3054   }
3055 
3056   case Instruction::Alloca: {
3057     Code = bitc::FUNC_CODE_INST_ALLOCA;
3058     const AllocaInst &AI = cast<AllocaInst>(I);
3059     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3060     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3061     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3062     using APV = AllocaPackedValues;
3063     unsigned Record = 0;
3064     unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3065     Bitfield::set<APV::AlignLower>(
3066         Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3067     Bitfield::set<APV::AlignUpper>(Record,
3068                                    EncodedAlign >> APV::AlignLower::Bits);
3069     Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3070     Bitfield::set<APV::ExplicitType>(Record, true);
3071     Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3072     Vals.push_back(Record);
3073     break;
3074   }
3075 
3076   case Instruction::Load:
3077     if (cast<LoadInst>(I).isAtomic()) {
3078       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
3079       pushValueAndType(I.getOperand(0), InstID, Vals);
3080     } else {
3081       Code = bitc::FUNC_CODE_INST_LOAD;
3082       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3083         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3084     }
3085     Vals.push_back(VE.getTypeID(I.getType()));
3086     Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3087     Vals.push_back(cast<LoadInst>(I).isVolatile());
3088     if (cast<LoadInst>(I).isAtomic()) {
3089       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3090       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3091     }
3092     break;
3093   case Instruction::Store:
3094     if (cast<StoreInst>(I).isAtomic())
3095       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
3096     else
3097       Code = bitc::FUNC_CODE_INST_STORE;
3098     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3099     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3100     Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3101     Vals.push_back(cast<StoreInst>(I).isVolatile());
3102     if (cast<StoreInst>(I).isAtomic()) {
3103       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3104       Vals.push_back(
3105           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3106     }
3107     break;
3108   case Instruction::AtomicCmpXchg:
3109     Code = bitc::FUNC_CODE_INST_CMPXCHG;
3110     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3111     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3112     pushValue(I.getOperand(2), InstID, Vals);        // newval.
3113     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3114     Vals.push_back(
3115         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3116     Vals.push_back(
3117         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3118     Vals.push_back(
3119         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3120     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3121     Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3122     break;
3123   case Instruction::AtomicRMW:
3124     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
3125     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3126     pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3127     Vals.push_back(
3128         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3129     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3130     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3131     Vals.push_back(
3132         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3133     Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3134     break;
3135   case Instruction::Fence:
3136     Code = bitc::FUNC_CODE_INST_FENCE;
3137     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3138     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3139     break;
3140   case Instruction::Call: {
3141     const CallInst &CI = cast<CallInst>(I);
3142     FunctionType *FTy = CI.getFunctionType();
3143 
3144     if (CI.hasOperandBundles())
3145       writeOperandBundles(CI, InstID);
3146 
3147     Code = bitc::FUNC_CODE_INST_CALL;
3148 
3149     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3150 
3151     unsigned Flags = getOptimizationFlags(&I);
3152     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3153                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3154                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3155                    1 << bitc::CALL_EXPLICIT_TYPE |
3156                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3157                    unsigned(Flags != 0) << bitc::CALL_FMF);
3158     if (Flags != 0)
3159       Vals.push_back(Flags);
3160 
3161     Vals.push_back(VE.getTypeID(FTy));
3162     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3163 
3164     // Emit value #'s for the fixed parameters.
3165     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3166       // Check for labels (can happen with asm labels).
3167       if (FTy->getParamType(i)->isLabelTy())
3168         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3169       else
3170         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3171     }
3172 
3173     // Emit type/value pairs for varargs params.
3174     if (FTy->isVarArg()) {
3175       for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3176         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3177     }
3178     break;
3179   }
3180   case Instruction::VAArg:
3181     Code = bitc::FUNC_CODE_INST_VAARG;
3182     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
3183     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
3184     Vals.push_back(VE.getTypeID(I.getType())); // restype.
3185     break;
3186   case Instruction::Freeze:
3187     Code = bitc::FUNC_CODE_INST_FREEZE;
3188     pushValueAndType(I.getOperand(0), InstID, Vals);
3189     break;
3190   }
3191 
3192   Stream.EmitRecord(Code, Vals, AbbrevToUse);
3193   Vals.clear();
3194 }
3195 
3196 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3197 /// to allow clients to efficiently find the function body.
3198 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3199   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3200   // Get the offset of the VST we are writing, and backpatch it into
3201   // the VST forward declaration record.
3202   uint64_t VSTOffset = Stream.GetCurrentBitNo();
3203   // The BitcodeStartBit was the stream offset of the identification block.
3204   VSTOffset -= bitcodeStartBit();
3205   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3206   // Note that we add 1 here because the offset is relative to one word
3207   // before the start of the identification block, which was historically
3208   // always the start of the regular bitcode header.
3209   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3210 
3211   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3212 
3213   auto Abbv = std::make_shared<BitCodeAbbrev>();
3214   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
3215   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3216   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3217   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3218 
3219   for (const Function &F : M) {
3220     uint64_t Record[2];
3221 
3222     if (F.isDeclaration())
3223       continue;
3224 
3225     Record[0] = VE.getValueID(&F);
3226 
3227     // Save the word offset of the function (from the start of the
3228     // actual bitcode written to the stream).
3229     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3230     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3231     // Note that we add 1 here because the offset is relative to one word
3232     // before the start of the identification block, which was historically
3233     // always the start of the regular bitcode header.
3234     Record[1] = BitcodeIndex / 32 + 1;
3235 
3236     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3237   }
3238 
3239   Stream.ExitBlock();
3240 }
3241 
3242 /// Emit names for arguments, instructions and basic blocks in a function.
3243 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3244     const ValueSymbolTable &VST) {
3245   if (VST.empty())
3246     return;
3247 
3248   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3249 
3250   // FIXME: Set up the abbrev, we know how many values there are!
3251   // FIXME: We know if the type names can use 7-bit ascii.
3252   SmallVector<uint64_t, 64> NameVals;
3253 
3254   for (const ValueName &Name : VST) {
3255     // Figure out the encoding to use for the name.
3256     StringEncoding Bits = getStringEncoding(Name.getKey());
3257 
3258     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3259     NameVals.push_back(VE.getValueID(Name.getValue()));
3260 
3261     // VST_CODE_ENTRY:   [valueid, namechar x N]
3262     // VST_CODE_BBENTRY: [bbid, namechar x N]
3263     unsigned Code;
3264     if (isa<BasicBlock>(Name.getValue())) {
3265       Code = bitc::VST_CODE_BBENTRY;
3266       if (Bits == SE_Char6)
3267         AbbrevToUse = VST_BBENTRY_6_ABBREV;
3268     } else {
3269       Code = bitc::VST_CODE_ENTRY;
3270       if (Bits == SE_Char6)
3271         AbbrevToUse = VST_ENTRY_6_ABBREV;
3272       else if (Bits == SE_Fixed7)
3273         AbbrevToUse = VST_ENTRY_7_ABBREV;
3274     }
3275 
3276     for (const auto P : Name.getKey())
3277       NameVals.push_back((unsigned char)P);
3278 
3279     // Emit the finished record.
3280     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3281     NameVals.clear();
3282   }
3283 
3284   Stream.ExitBlock();
3285 }
3286 
3287 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3288   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3289   unsigned Code;
3290   if (isa<BasicBlock>(Order.V))
3291     Code = bitc::USELIST_CODE_BB;
3292   else
3293     Code = bitc::USELIST_CODE_DEFAULT;
3294 
3295   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3296   Record.push_back(VE.getValueID(Order.V));
3297   Stream.EmitRecord(Code, Record);
3298 }
3299 
3300 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3301   assert(VE.shouldPreserveUseListOrder() &&
3302          "Expected to be preserving use-list order");
3303 
3304   auto hasMore = [&]() {
3305     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3306   };
3307   if (!hasMore())
3308     // Nothing to do.
3309     return;
3310 
3311   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3312   while (hasMore()) {
3313     writeUseList(std::move(VE.UseListOrders.back()));
3314     VE.UseListOrders.pop_back();
3315   }
3316   Stream.ExitBlock();
3317 }
3318 
3319 /// Emit a function body to the module stream.
3320 void ModuleBitcodeWriter::writeFunction(
3321     const Function &F,
3322     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3323   // Save the bitcode index of the start of this function block for recording
3324   // in the VST.
3325   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3326 
3327   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3328   VE.incorporateFunction(F);
3329 
3330   SmallVector<unsigned, 64> Vals;
3331 
3332   // Emit the number of basic blocks, so the reader can create them ahead of
3333   // time.
3334   Vals.push_back(VE.getBasicBlocks().size());
3335   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3336   Vals.clear();
3337 
3338   // If there are function-local constants, emit them now.
3339   unsigned CstStart, CstEnd;
3340   VE.getFunctionConstantRange(CstStart, CstEnd);
3341   writeConstants(CstStart, CstEnd, false);
3342 
3343   // If there is function-local metadata, emit it now.
3344   writeFunctionMetadata(F);
3345 
3346   // Keep a running idea of what the instruction ID is.
3347   unsigned InstID = CstEnd;
3348 
3349   bool NeedsMetadataAttachment = F.hasMetadata();
3350 
3351   DILocation *LastDL = nullptr;
3352   // Finally, emit all the instructions, in order.
3353   for (const BasicBlock &BB : F)
3354     for (const Instruction &I : BB) {
3355       writeInstruction(I, InstID, Vals);
3356 
3357       if (!I.getType()->isVoidTy())
3358         ++InstID;
3359 
3360       // If the instruction has metadata, write a metadata attachment later.
3361       NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3362 
3363       // If the instruction has a debug location, emit it.
3364       DILocation *DL = I.getDebugLoc();
3365       if (!DL)
3366         continue;
3367 
3368       if (DL == LastDL) {
3369         // Just repeat the same debug loc as last time.
3370         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3371         continue;
3372       }
3373 
3374       Vals.push_back(DL->getLine());
3375       Vals.push_back(DL->getColumn());
3376       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3377       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3378       Vals.push_back(DL->isImplicitCode());
3379       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3380       Vals.clear();
3381 
3382       LastDL = DL;
3383     }
3384 
3385   // Emit names for all the instructions etc.
3386   if (auto *Symtab = F.getValueSymbolTable())
3387     writeFunctionLevelValueSymbolTable(*Symtab);
3388 
3389   if (NeedsMetadataAttachment)
3390     writeFunctionMetadataAttachment(F);
3391   if (VE.shouldPreserveUseListOrder())
3392     writeUseListBlock(&F);
3393   VE.purgeFunction();
3394   Stream.ExitBlock();
3395 }
3396 
3397 // Emit blockinfo, which defines the standard abbreviations etc.
3398 void ModuleBitcodeWriter::writeBlockInfo() {
3399   // We only want to emit block info records for blocks that have multiple
3400   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3401   // Other blocks can define their abbrevs inline.
3402   Stream.EnterBlockInfoBlock();
3403 
3404   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3405     auto Abbv = std::make_shared<BitCodeAbbrev>();
3406     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3407     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3408     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3409     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3410     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3411         VST_ENTRY_8_ABBREV)
3412       llvm_unreachable("Unexpected abbrev ordering!");
3413   }
3414 
3415   { // 7-bit fixed width VST_CODE_ENTRY strings.
3416     auto Abbv = std::make_shared<BitCodeAbbrev>();
3417     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3418     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3419     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3420     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3421     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3422         VST_ENTRY_7_ABBREV)
3423       llvm_unreachable("Unexpected abbrev ordering!");
3424   }
3425   { // 6-bit char6 VST_CODE_ENTRY strings.
3426     auto Abbv = std::make_shared<BitCodeAbbrev>();
3427     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3428     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3429     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3430     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3431     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3432         VST_ENTRY_6_ABBREV)
3433       llvm_unreachable("Unexpected abbrev ordering!");
3434   }
3435   { // 6-bit char6 VST_CODE_BBENTRY strings.
3436     auto Abbv = std::make_shared<BitCodeAbbrev>();
3437     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3438     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3439     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3440     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3441     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3442         VST_BBENTRY_6_ABBREV)
3443       llvm_unreachable("Unexpected abbrev ordering!");
3444   }
3445 
3446   { // SETTYPE abbrev for CONSTANTS_BLOCK.
3447     auto Abbv = std::make_shared<BitCodeAbbrev>();
3448     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3449     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3450                               VE.computeBitsRequiredForTypeIndicies()));
3451     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3452         CONSTANTS_SETTYPE_ABBREV)
3453       llvm_unreachable("Unexpected abbrev ordering!");
3454   }
3455 
3456   { // INTEGER abbrev for CONSTANTS_BLOCK.
3457     auto Abbv = std::make_shared<BitCodeAbbrev>();
3458     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3459     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3460     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3461         CONSTANTS_INTEGER_ABBREV)
3462       llvm_unreachable("Unexpected abbrev ordering!");
3463   }
3464 
3465   { // CE_CAST abbrev for CONSTANTS_BLOCK.
3466     auto Abbv = std::make_shared<BitCodeAbbrev>();
3467     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3468     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
3469     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
3470                               VE.computeBitsRequiredForTypeIndicies()));
3471     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
3472 
3473     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3474         CONSTANTS_CE_CAST_Abbrev)
3475       llvm_unreachable("Unexpected abbrev ordering!");
3476   }
3477   { // NULL abbrev for CONSTANTS_BLOCK.
3478     auto Abbv = std::make_shared<BitCodeAbbrev>();
3479     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3480     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3481         CONSTANTS_NULL_Abbrev)
3482       llvm_unreachable("Unexpected abbrev ordering!");
3483   }
3484 
3485   // FIXME: This should only use space for first class types!
3486 
3487   { // INST_LOAD abbrev for FUNCTION_BLOCK.
3488     auto Abbv = std::make_shared<BitCodeAbbrev>();
3489     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3490     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3491     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
3492                               VE.computeBitsRequiredForTypeIndicies()));
3493     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3494     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3495     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3496         FUNCTION_INST_LOAD_ABBREV)
3497       llvm_unreachable("Unexpected abbrev ordering!");
3498   }
3499   { // INST_UNOP abbrev for FUNCTION_BLOCK.
3500     auto Abbv = std::make_shared<BitCodeAbbrev>();
3501     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3502     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3503     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3504     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3505         FUNCTION_INST_UNOP_ABBREV)
3506       llvm_unreachable("Unexpected abbrev ordering!");
3507   }
3508   { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3509     auto Abbv = std::make_shared<BitCodeAbbrev>();
3510     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3511     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3512     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3513     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3514     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3515         FUNCTION_INST_UNOP_FLAGS_ABBREV)
3516       llvm_unreachable("Unexpected abbrev ordering!");
3517   }
3518   { // INST_BINOP abbrev for FUNCTION_BLOCK.
3519     auto Abbv = std::make_shared<BitCodeAbbrev>();
3520     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3521     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3522     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3523     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3524     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3525         FUNCTION_INST_BINOP_ABBREV)
3526       llvm_unreachable("Unexpected abbrev ordering!");
3527   }
3528   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3529     auto Abbv = std::make_shared<BitCodeAbbrev>();
3530     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3531     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3532     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3533     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3534     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3535     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3536         FUNCTION_INST_BINOP_FLAGS_ABBREV)
3537       llvm_unreachable("Unexpected abbrev ordering!");
3538   }
3539   { // INST_CAST abbrev for FUNCTION_BLOCK.
3540     auto Abbv = std::make_shared<BitCodeAbbrev>();
3541     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3542     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
3543     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
3544                               VE.computeBitsRequiredForTypeIndicies()));
3545     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
3546     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3547         FUNCTION_INST_CAST_ABBREV)
3548       llvm_unreachable("Unexpected abbrev ordering!");
3549   }
3550 
3551   { // INST_RET abbrev for FUNCTION_BLOCK.
3552     auto Abbv = std::make_shared<BitCodeAbbrev>();
3553     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3554     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3555         FUNCTION_INST_RET_VOID_ABBREV)
3556       llvm_unreachable("Unexpected abbrev ordering!");
3557   }
3558   { // INST_RET abbrev for FUNCTION_BLOCK.
3559     auto Abbv = std::make_shared<BitCodeAbbrev>();
3560     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3561     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3562     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3563         FUNCTION_INST_RET_VAL_ABBREV)
3564       llvm_unreachable("Unexpected abbrev ordering!");
3565   }
3566   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3567     auto Abbv = std::make_shared<BitCodeAbbrev>();
3568     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3569     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3570         FUNCTION_INST_UNREACHABLE_ABBREV)
3571       llvm_unreachable("Unexpected abbrev ordering!");
3572   }
3573   {
3574     auto Abbv = std::make_shared<BitCodeAbbrev>();
3575     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3576     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3577     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3578                               Log2_32_Ceil(VE.getTypes().size() + 1)));
3579     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3580     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3581     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3582         FUNCTION_INST_GEP_ABBREV)
3583       llvm_unreachable("Unexpected abbrev ordering!");
3584   }
3585 
3586   Stream.ExitBlock();
3587 }
3588 
3589 /// Write the module path strings, currently only used when generating
3590 /// a combined index file.
3591 void IndexBitcodeWriter::writeModStrings() {
3592   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3593 
3594   // TODO: See which abbrev sizes we actually need to emit
3595 
3596   // 8-bit fixed-width MST_ENTRY strings.
3597   auto Abbv = std::make_shared<BitCodeAbbrev>();
3598   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3599   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3600   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3601   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3602   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3603 
3604   // 7-bit fixed width MST_ENTRY strings.
3605   Abbv = std::make_shared<BitCodeAbbrev>();
3606   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3607   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3608   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3609   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3610   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3611 
3612   // 6-bit char6 MST_ENTRY strings.
3613   Abbv = std::make_shared<BitCodeAbbrev>();
3614   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3615   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3616   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3617   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3618   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3619 
3620   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3621   Abbv = std::make_shared<BitCodeAbbrev>();
3622   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3623   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3624   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3625   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3626   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3627   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3628   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3629 
3630   SmallVector<unsigned, 64> Vals;
3631   forEachModule(
3632       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3633         StringRef Key = MPSE.getKey();
3634         const auto &Value = MPSE.getValue();
3635         StringEncoding Bits = getStringEncoding(Key);
3636         unsigned AbbrevToUse = Abbrev8Bit;
3637         if (Bits == SE_Char6)
3638           AbbrevToUse = Abbrev6Bit;
3639         else if (Bits == SE_Fixed7)
3640           AbbrevToUse = Abbrev7Bit;
3641 
3642         Vals.push_back(Value.first);
3643         Vals.append(Key.begin(), Key.end());
3644 
3645         // Emit the finished record.
3646         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3647 
3648         // Emit an optional hash for the module now
3649         const auto &Hash = Value.second;
3650         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3651           Vals.assign(Hash.begin(), Hash.end());
3652           // Emit the hash record.
3653           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3654         }
3655 
3656         Vals.clear();
3657       });
3658   Stream.ExitBlock();
3659 }
3660 
3661 /// Write the function type metadata related records that need to appear before
3662 /// a function summary entry (whether per-module or combined).
3663 template <typename Fn>
3664 static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3665                                              FunctionSummary *FS,
3666                                              Fn GetValueID) {
3667   if (!FS->type_tests().empty())
3668     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3669 
3670   SmallVector<uint64_t, 64> Record;
3671 
3672   auto WriteVFuncIdVec = [&](uint64_t Ty,
3673                              ArrayRef<FunctionSummary::VFuncId> VFs) {
3674     if (VFs.empty())
3675       return;
3676     Record.clear();
3677     for (auto &VF : VFs) {
3678       Record.push_back(VF.GUID);
3679       Record.push_back(VF.Offset);
3680     }
3681     Stream.EmitRecord(Ty, Record);
3682   };
3683 
3684   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3685                   FS->type_test_assume_vcalls());
3686   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3687                   FS->type_checked_load_vcalls());
3688 
3689   auto WriteConstVCallVec = [&](uint64_t Ty,
3690                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3691     for (auto &VC : VCs) {
3692       Record.clear();
3693       Record.push_back(VC.VFunc.GUID);
3694       Record.push_back(VC.VFunc.Offset);
3695       llvm::append_range(Record, VC.Args);
3696       Stream.EmitRecord(Ty, Record);
3697     }
3698   };
3699 
3700   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3701                      FS->type_test_assume_const_vcalls());
3702   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3703                      FS->type_checked_load_const_vcalls());
3704 
3705   auto WriteRange = [&](ConstantRange Range) {
3706     Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3707     assert(Range.getLower().getNumWords() == 1);
3708     assert(Range.getUpper().getNumWords() == 1);
3709     emitSignedInt64(Record, *Range.getLower().getRawData());
3710     emitSignedInt64(Record, *Range.getUpper().getRawData());
3711   };
3712 
3713   if (!FS->paramAccesses().empty()) {
3714     Record.clear();
3715     for (auto &Arg : FS->paramAccesses()) {
3716       size_t UndoSize = Record.size();
3717       Record.push_back(Arg.ParamNo);
3718       WriteRange(Arg.Use);
3719       Record.push_back(Arg.Calls.size());
3720       for (auto &Call : Arg.Calls) {
3721         Record.push_back(Call.ParamNo);
3722         Optional<unsigned> ValueID = GetValueID(Call.Callee);
3723         if (!ValueID) {
3724           // If ValueID is unknown we can't drop just this call, we must drop
3725           // entire parameter.
3726           Record.resize(UndoSize);
3727           break;
3728         }
3729         Record.push_back(*ValueID);
3730         WriteRange(Call.Offsets);
3731       }
3732     }
3733     if (!Record.empty())
3734       Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
3735   }
3736 }
3737 
3738 /// Collect type IDs from type tests used by function.
3739 static void
3740 getReferencedTypeIds(FunctionSummary *FS,
3741                      std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3742   if (!FS->type_tests().empty())
3743     for (auto &TT : FS->type_tests())
3744       ReferencedTypeIds.insert(TT);
3745 
3746   auto GetReferencedTypesFromVFuncIdVec =
3747       [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3748         for (auto &VF : VFs)
3749           ReferencedTypeIds.insert(VF.GUID);
3750       };
3751 
3752   GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3753   GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3754 
3755   auto GetReferencedTypesFromConstVCallVec =
3756       [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3757         for (auto &VC : VCs)
3758           ReferencedTypeIds.insert(VC.VFunc.GUID);
3759       };
3760 
3761   GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3762   GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3763 }
3764 
3765 static void writeWholeProgramDevirtResolutionByArg(
3766     SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3767     const WholeProgramDevirtResolution::ByArg &ByArg) {
3768   NameVals.push_back(args.size());
3769   llvm::append_range(NameVals, args);
3770 
3771   NameVals.push_back(ByArg.TheKind);
3772   NameVals.push_back(ByArg.Info);
3773   NameVals.push_back(ByArg.Byte);
3774   NameVals.push_back(ByArg.Bit);
3775 }
3776 
3777 static void writeWholeProgramDevirtResolution(
3778     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3779     uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3780   NameVals.push_back(Id);
3781 
3782   NameVals.push_back(Wpd.TheKind);
3783   NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3784   NameVals.push_back(Wpd.SingleImplName.size());
3785 
3786   NameVals.push_back(Wpd.ResByArg.size());
3787   for (auto &A : Wpd.ResByArg)
3788     writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3789 }
3790 
3791 static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3792                                      StringTableBuilder &StrtabBuilder,
3793                                      const std::string &Id,
3794                                      const TypeIdSummary &Summary) {
3795   NameVals.push_back(StrtabBuilder.add(Id));
3796   NameVals.push_back(Id.size());
3797 
3798   NameVals.push_back(Summary.TTRes.TheKind);
3799   NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3800   NameVals.push_back(Summary.TTRes.AlignLog2);
3801   NameVals.push_back(Summary.TTRes.SizeM1);
3802   NameVals.push_back(Summary.TTRes.BitMask);
3803   NameVals.push_back(Summary.TTRes.InlineBits);
3804 
3805   for (auto &W : Summary.WPDRes)
3806     writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3807                                       W.second);
3808 }
3809 
3810 static void writeTypeIdCompatibleVtableSummaryRecord(
3811     SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3812     const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3813     ValueEnumerator &VE) {
3814   NameVals.push_back(StrtabBuilder.add(Id));
3815   NameVals.push_back(Id.size());
3816 
3817   for (auto &P : Summary) {
3818     NameVals.push_back(P.AddressPointOffset);
3819     NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3820   }
3821 }
3822 
3823 // Helper to emit a single function summary record.
3824 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3825     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3826     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3827     const Function &F) {
3828   NameVals.push_back(ValueID);
3829 
3830   FunctionSummary *FS = cast<FunctionSummary>(Summary);
3831 
3832   writeFunctionTypeMetadataRecords(
3833       Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3834         return {VE.getValueID(VI.getValue())};
3835       });
3836 
3837   auto SpecialRefCnts = FS->specialRefCounts();
3838   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3839   NameVals.push_back(FS->instCount());
3840   NameVals.push_back(getEncodedFFlags(FS->fflags()));
3841   NameVals.push_back(FS->refs().size());
3842   NameVals.push_back(SpecialRefCnts.first);  // rorefcnt
3843   NameVals.push_back(SpecialRefCnts.second); // worefcnt
3844 
3845   for (auto &RI : FS->refs())
3846     NameVals.push_back(VE.getValueID(RI.getValue()));
3847 
3848   bool HasProfileData =
3849       F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3850   for (auto &ECI : FS->calls()) {
3851     NameVals.push_back(getValueId(ECI.first));
3852     if (HasProfileData)
3853       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3854     else if (WriteRelBFToSummary)
3855       NameVals.push_back(ECI.second.RelBlockFreq);
3856   }
3857 
3858   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3859   unsigned Code =
3860       (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3861                       : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3862                                              : bitc::FS_PERMODULE));
3863 
3864   // Emit the finished record.
3865   Stream.EmitRecord(Code, NameVals, FSAbbrev);
3866   NameVals.clear();
3867 }
3868 
3869 // Collect the global value references in the given variable's initializer,
3870 // and emit them in a summary record.
3871 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3872     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3873     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3874   auto VI = Index->getValueInfo(V.getGUID());
3875   if (!VI || VI.getSummaryList().empty()) {
3876     // Only declarations should not have a summary (a declaration might however
3877     // have a summary if the def was in module level asm).
3878     assert(V.isDeclaration());
3879     return;
3880   }
3881   auto *Summary = VI.getSummaryList()[0].get();
3882   NameVals.push_back(VE.getValueID(&V));
3883   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3884   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3885   NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3886 
3887   auto VTableFuncs = VS->vTableFuncs();
3888   if (!VTableFuncs.empty())
3889     NameVals.push_back(VS->refs().size());
3890 
3891   unsigned SizeBeforeRefs = NameVals.size();
3892   for (auto &RI : VS->refs())
3893     NameVals.push_back(VE.getValueID(RI.getValue()));
3894   // Sort the refs for determinism output, the vector returned by FS->refs() has
3895   // been initialized from a DenseSet.
3896   llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
3897 
3898   if (VTableFuncs.empty())
3899     Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3900                       FSModRefsAbbrev);
3901   else {
3902     // VTableFuncs pairs should already be sorted by offset.
3903     for (auto &P : VTableFuncs) {
3904       NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3905       NameVals.push_back(P.VTableOffset);
3906     }
3907 
3908     Stream.EmitRecord(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS, NameVals,
3909                       FSModVTableRefsAbbrev);
3910   }
3911   NameVals.clear();
3912 }
3913 
3914 /// Emit the per-module summary section alongside the rest of
3915 /// the module's bitcode.
3916 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3917   // By default we compile with ThinLTO if the module has a summary, but the
3918   // client can request full LTO with a module flag.
3919   bool IsThinLTO = true;
3920   if (auto *MD =
3921           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3922     IsThinLTO = MD->getZExtValue();
3923   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3924                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3925                        4);
3926 
3927   Stream.EmitRecord(
3928       bitc::FS_VERSION,
3929       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
3930 
3931   // Write the index flags.
3932   uint64_t Flags = 0;
3933   // Bits 1-3 are set only in the combined index, skip them.
3934   if (Index->enableSplitLTOUnit())
3935     Flags |= 0x8;
3936   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3937 
3938   if (Index->begin() == Index->end()) {
3939     Stream.ExitBlock();
3940     return;
3941   }
3942 
3943   for (const auto &GVI : valueIds()) {
3944     Stream.EmitRecord(bitc::FS_VALUE_GUID,
3945                       ArrayRef<uint64_t>{GVI.second, GVI.first});
3946   }
3947 
3948   // Abbrev for FS_PERMODULE_PROFILE.
3949   auto Abbv = std::make_shared<BitCodeAbbrev>();
3950   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3951   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3952   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3953   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3954   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3955   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3956   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3957   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3958   // numrefs x valueid, n x (valueid, hotness)
3959   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3960   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3961   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3962 
3963   // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3964   Abbv = std::make_shared<BitCodeAbbrev>();
3965   if (WriteRelBFToSummary)
3966     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3967   else
3968     Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3969   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
3970   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
3971   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
3972   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
3973   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
3974   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
3975   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
3976   // numrefs x valueid, n x (valueid [, rel_block_freq])
3977   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3978   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3979   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3980 
3981   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3982   Abbv = std::make_shared<BitCodeAbbrev>();
3983   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3984   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3985   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3986   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
3987   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3988   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3989 
3990   // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
3991   Abbv = std::make_shared<BitCodeAbbrev>();
3992   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS));
3993   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3994   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3995   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3996   // numrefs x valueid, n x (valueid , offset)
3997   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3998   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3999   unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4000 
4001   // Abbrev for FS_ALIAS.
4002   Abbv = std::make_shared<BitCodeAbbrev>();
4003   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4004   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4005   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4006   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4007   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4008 
4009   // Abbrev for FS_TYPE_ID_METADATA
4010   Abbv = std::make_shared<BitCodeAbbrev>();
4011   Abbv->Add(BitCodeAbbrevOp(bitc::FS_TYPE_ID_METADATA));
4012   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4013   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4014   // n x (valueid , offset)
4015   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4016   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4017   unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4018 
4019   SmallVector<uint64_t, 64> NameVals;
4020   // Iterate over the list of functions instead of the Index to
4021   // ensure the ordering is stable.
4022   for (const Function &F : M) {
4023     // Summary emission does not support anonymous functions, they have to
4024     // renamed using the anonymous function renaming pass.
4025     if (!F.hasName())
4026       report_fatal_error("Unexpected anonymous function when writing summary");
4027 
4028     ValueInfo VI = Index->getValueInfo(F.getGUID());
4029     if (!VI || VI.getSummaryList().empty()) {
4030       // Only declarations should not have a summary (a declaration might
4031       // however have a summary if the def was in module level asm).
4032       assert(F.isDeclaration());
4033       continue;
4034     }
4035     auto *Summary = VI.getSummaryList()[0].get();
4036     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4037                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
4038   }
4039 
4040   // Capture references from GlobalVariable initializers, which are outside
4041   // of a function scope.
4042   for (const GlobalVariable &G : M.globals())
4043     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4044                                FSModVTableRefsAbbrev);
4045 
4046   for (const GlobalAlias &A : M.aliases()) {
4047     auto *Aliasee = A.getAliaseeObject();
4048     if (!Aliasee->hasName())
4049       // Nameless function don't have an entry in the summary, skip it.
4050       continue;
4051     auto AliasId = VE.getValueID(&A);
4052     auto AliaseeId = VE.getValueID(Aliasee);
4053     NameVals.push_back(AliasId);
4054     auto *Summary = Index->getGlobalValueSummary(A);
4055     AliasSummary *AS = cast<AliasSummary>(Summary);
4056     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4057     NameVals.push_back(AliaseeId);
4058     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4059     NameVals.clear();
4060   }
4061 
4062   for (auto &S : Index->typeIdCompatibleVtableMap()) {
4063     writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4064                                              S.second, VE);
4065     Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4066                       TypeIdCompatibleVtableAbbrev);
4067     NameVals.clear();
4068   }
4069 
4070   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4071                     ArrayRef<uint64_t>{Index->getBlockCount()});
4072 
4073   Stream.ExitBlock();
4074 }
4075 
4076 /// Emit the combined summary section into the combined index file.
4077 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4078   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
4079   Stream.EmitRecord(
4080       bitc::FS_VERSION,
4081       ArrayRef<uint64_t>{ModuleSummaryIndex::BitcodeSummaryVersion});
4082 
4083   // Write the index flags.
4084   Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4085 
4086   for (const auto &GVI : valueIds()) {
4087     Stream.EmitRecord(bitc::FS_VALUE_GUID,
4088                       ArrayRef<uint64_t>{GVI.second, GVI.first});
4089   }
4090 
4091   // Abbrev for FS_COMBINED.
4092   auto Abbv = std::make_shared<BitCodeAbbrev>();
4093   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
4094   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4095   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4096   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4097   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4098   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4099   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4100   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4101   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4102   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4103   // numrefs x valueid, n x (valueid)
4104   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4105   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4106   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4107 
4108   // Abbrev for FS_COMBINED_PROFILE.
4109   Abbv = std::make_shared<BitCodeAbbrev>();
4110   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
4111   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4112   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4113   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4114   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
4115   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
4116   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // entrycount
4117   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
4118   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // rorefcnt
4119   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // worefcnt
4120   // numrefs x valueid, n x (valueid, hotness)
4121   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4122   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4123   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4124 
4125   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4126   Abbv = std::make_shared<BitCodeAbbrev>();
4127   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
4128   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4129   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4130   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4131   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
4132   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4133   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4134 
4135   // Abbrev for FS_COMBINED_ALIAS.
4136   Abbv = std::make_shared<BitCodeAbbrev>();
4137   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
4138   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4139   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
4140   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
4141   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
4142   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4143 
4144   // The aliases are emitted as a post-pass, and will point to the value
4145   // id of the aliasee. Save them in a vector for post-processing.
4146   SmallVector<AliasSummary *, 64> Aliases;
4147 
4148   // Save the value id for each summary for alias emission.
4149   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
4150 
4151   SmallVector<uint64_t, 64> NameVals;
4152 
4153   // Set that will be populated during call to writeFunctionTypeMetadataRecords
4154   // with the type ids referenced by this index file.
4155   std::set<GlobalValue::GUID> ReferencedTypeIds;
4156 
4157   // For local linkage, we also emit the original name separately
4158   // immediately after the record.
4159   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4160     // We don't need to emit the original name if we are writing the index for
4161     // distributed backends (in which case ModuleToSummariesForIndex is
4162     // non-null). The original name is only needed during the thin link, since
4163     // for SamplePGO the indirect call targets for local functions have
4164     // have the original name annotated in profile.
4165     // Continue to emit it when writing out the entire combined index, which is
4166     // used in testing the thin link via llvm-lto.
4167     if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4168       return;
4169     NameVals.push_back(S.getOriginalName());
4170     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4171     NameVals.clear();
4172   };
4173 
4174   std::set<GlobalValue::GUID> DefOrUseGUIDs;
4175   forEachSummary([&](GVInfo I, bool IsAliasee) {
4176     GlobalValueSummary *S = I.second;
4177     assert(S);
4178     DefOrUseGUIDs.insert(I.first);
4179     for (const ValueInfo &VI : S->refs())
4180       DefOrUseGUIDs.insert(VI.getGUID());
4181 
4182     auto ValueId = getValueId(I.first);
4183     assert(ValueId);
4184     SummaryToValueIdMap[S] = *ValueId;
4185 
4186     // If this is invoked for an aliasee, we want to record the above
4187     // mapping, but then not emit a summary entry (if the aliasee is
4188     // to be imported, we will invoke this separately with IsAliasee=false).
4189     if (IsAliasee)
4190       return;
4191 
4192     if (auto *AS = dyn_cast<AliasSummary>(S)) {
4193       // Will process aliases as a post-pass because the reader wants all
4194       // global to be loaded first.
4195       Aliases.push_back(AS);
4196       return;
4197     }
4198 
4199     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4200       NameVals.push_back(*ValueId);
4201       NameVals.push_back(Index.getModuleId(VS->modulePath()));
4202       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4203       NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4204       for (auto &RI : VS->refs()) {
4205         auto RefValueId = getValueId(RI.getGUID());
4206         if (!RefValueId)
4207           continue;
4208         NameVals.push_back(*RefValueId);
4209       }
4210 
4211       // Emit the finished record.
4212       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4213                         FSModRefsAbbrev);
4214       NameVals.clear();
4215       MaybeEmitOriginalName(*S);
4216       return;
4217     }
4218 
4219     auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4220       return getValueId(VI.getGUID());
4221     };
4222 
4223     auto *FS = cast<FunctionSummary>(S);
4224     writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4225     getReferencedTypeIds(FS, ReferencedTypeIds);
4226 
4227     NameVals.push_back(*ValueId);
4228     NameVals.push_back(Index.getModuleId(FS->modulePath()));
4229     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4230     NameVals.push_back(FS->instCount());
4231     NameVals.push_back(getEncodedFFlags(FS->fflags()));
4232     NameVals.push_back(FS->entryCount());
4233 
4234     // Fill in below
4235     NameVals.push_back(0); // numrefs
4236     NameVals.push_back(0); // rorefcnt
4237     NameVals.push_back(0); // worefcnt
4238 
4239     unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4240     for (auto &RI : FS->refs()) {
4241       auto RefValueId = getValueId(RI.getGUID());
4242       if (!RefValueId)
4243         continue;
4244       NameVals.push_back(*RefValueId);
4245       if (RI.isReadOnly())
4246         RORefCnt++;
4247       else if (RI.isWriteOnly())
4248         WORefCnt++;
4249       Count++;
4250     }
4251     NameVals[6] = Count;
4252     NameVals[7] = RORefCnt;
4253     NameVals[8] = WORefCnt;
4254 
4255     bool HasProfileData = false;
4256     for (auto &EI : FS->calls()) {
4257       HasProfileData |=
4258           EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4259       if (HasProfileData)
4260         break;
4261     }
4262 
4263     for (auto &EI : FS->calls()) {
4264       // If this GUID doesn't have a value id, it doesn't have a function
4265       // summary and we don't need to record any calls to it.
4266       Optional<unsigned> CallValueId = GetValueId(EI.first);
4267       if (!CallValueId)
4268         continue;
4269       NameVals.push_back(*CallValueId);
4270       if (HasProfileData)
4271         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4272     }
4273 
4274     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4275     unsigned Code =
4276         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4277 
4278     // Emit the finished record.
4279     Stream.EmitRecord(Code, NameVals, FSAbbrev);
4280     NameVals.clear();
4281     MaybeEmitOriginalName(*S);
4282   });
4283 
4284   for (auto *AS : Aliases) {
4285     auto AliasValueId = SummaryToValueIdMap[AS];
4286     assert(AliasValueId);
4287     NameVals.push_back(AliasValueId);
4288     NameVals.push_back(Index.getModuleId(AS->modulePath()));
4289     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4290     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4291     assert(AliaseeValueId);
4292     NameVals.push_back(AliaseeValueId);
4293 
4294     // Emit the finished record.
4295     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4296     NameVals.clear();
4297     MaybeEmitOriginalName(*AS);
4298 
4299     if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4300       getReferencedTypeIds(FS, ReferencedTypeIds);
4301   }
4302 
4303   if (!Index.cfiFunctionDefs().empty()) {
4304     for (auto &S : Index.cfiFunctionDefs()) {
4305       if (DefOrUseGUIDs.count(
4306               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4307         NameVals.push_back(StrtabBuilder.add(S));
4308         NameVals.push_back(S.size());
4309       }
4310     }
4311     if (!NameVals.empty()) {
4312       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4313       NameVals.clear();
4314     }
4315   }
4316 
4317   if (!Index.cfiFunctionDecls().empty()) {
4318     for (auto &S : Index.cfiFunctionDecls()) {
4319       if (DefOrUseGUIDs.count(
4320               GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(S)))) {
4321         NameVals.push_back(StrtabBuilder.add(S));
4322         NameVals.push_back(S.size());
4323       }
4324     }
4325     if (!NameVals.empty()) {
4326       Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4327       NameVals.clear();
4328     }
4329   }
4330 
4331   // Walk the GUIDs that were referenced, and write the
4332   // corresponding type id records.
4333   for (auto &T : ReferencedTypeIds) {
4334     auto TidIter = Index.typeIds().equal_range(T);
4335     for (auto It = TidIter.first; It != TidIter.second; ++It) {
4336       writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4337                                It->second.second);
4338       Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4339       NameVals.clear();
4340     }
4341   }
4342 
4343   Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4344                     ArrayRef<uint64_t>{Index.getBlockCount()});
4345 
4346   Stream.ExitBlock();
4347 }
4348 
4349 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4350 /// current llvm version, and a record for the epoch number.
4351 static void writeIdentificationBlock(BitstreamWriter &Stream) {
4352   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4353 
4354   // Write the "user readable" string identifying the bitcode producer
4355   auto Abbv = std::make_shared<BitCodeAbbrev>();
4356   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
4357   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4358   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
4359   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4360   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
4361                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4362 
4363   // Write the epoch version
4364   Abbv = std::make_shared<BitCodeAbbrev>();
4365   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
4366   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4367   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4368   constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4369   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4370   Stream.ExitBlock();
4371 }
4372 
4373 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4374   // Emit the module's hash.
4375   // MODULE_CODE_HASH: [5*i32]
4376   if (GenerateHash) {
4377     uint32_t Vals[5];
4378     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4379                                     Buffer.size() - BlockStartPos));
4380     StringRef Hash = Hasher.result();
4381     for (int Pos = 0; Pos < 20; Pos += 4) {
4382       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4383     }
4384 
4385     // Emit the finished record.
4386     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4387 
4388     if (ModHash)
4389       // Save the written hash value.
4390       llvm::copy(Vals, std::begin(*ModHash));
4391   }
4392 }
4393 
4394 void ModuleBitcodeWriter::write() {
4395   writeIdentificationBlock(Stream);
4396 
4397   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4398   size_t BlockStartPos = Buffer.size();
4399 
4400   writeModuleVersion();
4401 
4402   // Emit blockinfo, which defines the standard abbreviations etc.
4403   writeBlockInfo();
4404 
4405   // Emit information describing all of the types in the module.
4406   writeTypeTable();
4407 
4408   // Emit information about attribute groups.
4409   writeAttributeGroupTable();
4410 
4411   // Emit information about parameter attributes.
4412   writeAttributeTable();
4413 
4414   writeComdats();
4415 
4416   // Emit top-level description of module, including target triple, inline asm,
4417   // descriptors for global variables, and function prototype info.
4418   writeModuleInfo();
4419 
4420   // Emit constants.
4421   writeModuleConstants();
4422 
4423   // Emit metadata kind names.
4424   writeModuleMetadataKinds();
4425 
4426   // Emit metadata.
4427   writeModuleMetadata();
4428 
4429   // Emit module-level use-lists.
4430   if (VE.shouldPreserveUseListOrder())
4431     writeUseListBlock(nullptr);
4432 
4433   writeOperandBundleTags();
4434   writeSyncScopeNames();
4435 
4436   // Emit function bodies.
4437   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4438   for (const Function &F : M)
4439     if (!F.isDeclaration())
4440       writeFunction(F, FunctionToBitcodeIndex);
4441 
4442   // Need to write after the above call to WriteFunction which populates
4443   // the summary information in the index.
4444   if (Index)
4445     writePerModuleGlobalValueSummary();
4446 
4447   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4448 
4449   writeModuleHash(BlockStartPos);
4450 
4451   Stream.ExitBlock();
4452 }
4453 
4454 static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4455                                uint32_t &Position) {
4456   support::endian::write32le(&Buffer[Position], Value);
4457   Position += 4;
4458 }
4459 
4460 /// If generating a bc file on darwin, we have to emit a
4461 /// header and trailer to make it compatible with the system archiver.  To do
4462 /// this we emit the following header, and then emit a trailer that pads the
4463 /// file out to be a multiple of 16 bytes.
4464 ///
4465 /// struct bc_header {
4466 ///   uint32_t Magic;         // 0x0B17C0DE
4467 ///   uint32_t Version;       // Version, currently always 0.
4468 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4469 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
4470 ///   uint32_t CPUType;       // CPU specifier.
4471 ///   ... potentially more later ...
4472 /// };
4473 static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
4474                                          const Triple &TT) {
4475   unsigned CPUType = ~0U;
4476 
4477   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4478   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4479   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
4480   // specific constants here because they are implicitly part of the Darwin ABI.
4481   enum {
4482     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
4483     DARWIN_CPU_TYPE_X86        = 7,
4484     DARWIN_CPU_TYPE_ARM        = 12,
4485     DARWIN_CPU_TYPE_POWERPC    = 18
4486   };
4487 
4488   Triple::ArchType Arch = TT.getArch();
4489   if (Arch == Triple::x86_64)
4490     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4491   else if (Arch == Triple::x86)
4492     CPUType = DARWIN_CPU_TYPE_X86;
4493   else if (Arch == Triple::ppc)
4494     CPUType = DARWIN_CPU_TYPE_POWERPC;
4495   else if (Arch == Triple::ppc64)
4496     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4497   else if (Arch == Triple::arm || Arch == Triple::thumb)
4498     CPUType = DARWIN_CPU_TYPE_ARM;
4499 
4500   // Traditional Bitcode starts after header.
4501   assert(Buffer.size() >= BWH_HeaderSize &&
4502          "Expected header size to be reserved");
4503   unsigned BCOffset = BWH_HeaderSize;
4504   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4505 
4506   // Write the magic and version.
4507   unsigned Position = 0;
4508   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4509   writeInt32ToBuffer(0, Buffer, Position); // Version.
4510   writeInt32ToBuffer(BCOffset, Buffer, Position);
4511   writeInt32ToBuffer(BCSize, Buffer, Position);
4512   writeInt32ToBuffer(CPUType, Buffer, Position);
4513 
4514   // If the file is not a multiple of 16 bytes, insert dummy padding.
4515   while (Buffer.size() & 15)
4516     Buffer.push_back(0);
4517 }
4518 
4519 /// Helper to write the header common to all bitcode files.
4520 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4521   // Emit the file header.
4522   Stream.Emit((unsigned)'B', 8);
4523   Stream.Emit((unsigned)'C', 8);
4524   Stream.Emit(0x0, 4);
4525   Stream.Emit(0xC, 4);
4526   Stream.Emit(0xE, 4);
4527   Stream.Emit(0xD, 4);
4528 }
4529 
4530 BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer, raw_fd_stream *FS)
4531     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
4532   writeBitcodeHeader(*Stream);
4533 }
4534 
4535 BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4536 
4537 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4538   Stream->EnterSubblock(Block, 3);
4539 
4540   auto Abbv = std::make_shared<BitCodeAbbrev>();
4541   Abbv->Add(BitCodeAbbrevOp(Record));
4542   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4543   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4544 
4545   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4546 
4547   Stream->ExitBlock();
4548 }
4549 
4550 void BitcodeWriter::writeSymtab() {
4551   assert(!WroteStrtab && !WroteSymtab);
4552 
4553   // If any module has module-level inline asm, we will require a registered asm
4554   // parser for the target so that we can create an accurate symbol table for
4555   // the module.
4556   for (Module *M : Mods) {
4557     if (M->getModuleInlineAsm().empty())
4558       continue;
4559 
4560     std::string Err;
4561     const Triple TT(M->getTargetTriple());
4562     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4563     if (!T || !T->hasMCAsmParser())
4564       return;
4565   }
4566 
4567   WroteSymtab = true;
4568   SmallVector<char, 0> Symtab;
4569   // The irsymtab::build function may be unable to create a symbol table if the
4570   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4571   // table is not required for correctness, but we still want to be able to
4572   // write malformed modules to bitcode files, so swallow the error.
4573   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4574     consumeError(std::move(E));
4575     return;
4576   }
4577 
4578   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4579             {Symtab.data(), Symtab.size()});
4580 }
4581 
4582 void BitcodeWriter::writeStrtab() {
4583   assert(!WroteStrtab);
4584 
4585   std::vector<char> Strtab;
4586   StrtabBuilder.finalizeInOrder();
4587   Strtab.resize(StrtabBuilder.getSize());
4588   StrtabBuilder.write((uint8_t *)Strtab.data());
4589 
4590   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4591             {Strtab.data(), Strtab.size()});
4592 
4593   WroteStrtab = true;
4594 }
4595 
4596 void BitcodeWriter::copyStrtab(StringRef Strtab) {
4597   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4598   WroteStrtab = true;
4599 }
4600 
4601 void BitcodeWriter::writeModule(const Module &M,
4602                                 bool ShouldPreserveUseListOrder,
4603                                 const ModuleSummaryIndex *Index,
4604                                 bool GenerateHash, ModuleHash *ModHash) {
4605   assert(!WroteStrtab);
4606 
4607   // The Mods vector is used by irsymtab::build, which requires non-const
4608   // Modules in case it needs to materialize metadata. But the bitcode writer
4609   // requires that the module is materialized, so we can cast to non-const here,
4610   // after checking that it is in fact materialized.
4611   assert(M.isMaterialized());
4612   Mods.push_back(const_cast<Module *>(&M));
4613 
4614   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4615                                    ShouldPreserveUseListOrder, Index,
4616                                    GenerateHash, ModHash);
4617   ModuleWriter.write();
4618 }
4619 
4620 void BitcodeWriter::writeIndex(
4621     const ModuleSummaryIndex *Index,
4622     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4623   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4624                                  ModuleToSummariesForIndex);
4625   IndexWriter.write();
4626 }
4627 
4628 /// Write the specified module to the specified output stream.
4629 void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
4630                               bool ShouldPreserveUseListOrder,
4631                               const ModuleSummaryIndex *Index,
4632                               bool GenerateHash, ModuleHash *ModHash) {
4633   SmallVector<char, 0> Buffer;
4634   Buffer.reserve(256*1024);
4635 
4636   // If this is darwin or another generic macho target, reserve space for the
4637   // header.
4638   Triple TT(M.getTargetTriple());
4639   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4640     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
4641 
4642   BitcodeWriter Writer(Buffer, dyn_cast<raw_fd_stream>(&Out));
4643   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4644                      ModHash);
4645   Writer.writeSymtab();
4646   Writer.writeStrtab();
4647 
4648   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
4649     emitDarwinBCHeaderAndTrailer(Buffer, TT);
4650 
4651   // Write the generated bitstream to "Out".
4652   if (!Buffer.empty())
4653     Out.write((char *)&Buffer.front(), Buffer.size());
4654 }
4655 
4656 void IndexBitcodeWriter::write() {
4657   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4658 
4659   writeModuleVersion();
4660 
4661   // Write the module paths in the combined index.
4662   writeModStrings();
4663 
4664   // Write the summary combined index records.
4665   writeCombinedGlobalValueSummary();
4666 
4667   Stream.ExitBlock();
4668 }
4669 
4670 // Write the specified module summary index to the given raw output stream,
4671 // where it will be written in a new bitcode block. This is used when
4672 // writing the combined index file for ThinLTO. When writing a subset of the
4673 // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4674 void llvm::writeIndexToFile(
4675     const ModuleSummaryIndex &Index, raw_ostream &Out,
4676     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4677   SmallVector<char, 0> Buffer;
4678   Buffer.reserve(256 * 1024);
4679 
4680   BitcodeWriter Writer(Buffer);
4681   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4682   Writer.writeStrtab();
4683 
4684   Out.write((char *)&Buffer.front(), Buffer.size());
4685 }
4686 
4687 namespace {
4688 
4689 /// Class to manage the bitcode writing for a thin link bitcode file.
4690 class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4691   /// ModHash is for use in ThinLTO incremental build, generated while writing
4692   /// the module bitcode file.
4693   const ModuleHash *ModHash;
4694 
4695 public:
4696   ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
4697                         BitstreamWriter &Stream,
4698                         const ModuleSummaryIndex &Index,
4699                         const ModuleHash &ModHash)
4700       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4701                                 /*ShouldPreserveUseListOrder=*/false, &Index),
4702         ModHash(&ModHash) {}
4703 
4704   void write();
4705 
4706 private:
4707   void writeSimplifiedModuleInfo();
4708 };
4709 
4710 } // end anonymous namespace
4711 
4712 // This function writes a simpilified module info for thin link bitcode file.
4713 // It only contains the source file name along with the name(the offset and
4714 // size in strtab) and linkage for global values. For the global value info
4715 // entry, in order to keep linkage at offset 5, there are three zeros used
4716 // as padding.
4717 void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4718   SmallVector<unsigned, 64> Vals;
4719   // Emit the module's source file name.
4720   {
4721     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4722     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4723     if (Bits == SE_Char6)
4724       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4725     else if (Bits == SE_Fixed7)
4726       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4727 
4728     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4729     auto Abbv = std::make_shared<BitCodeAbbrev>();
4730     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4731     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4732     Abbv->Add(AbbrevOpToUse);
4733     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4734 
4735     for (const auto P : M.getSourceFileName())
4736       Vals.push_back((unsigned char)P);
4737 
4738     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4739     Vals.clear();
4740   }
4741 
4742   // Emit the global variable information.
4743   for (const GlobalVariable &GV : M.globals()) {
4744     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4745     Vals.push_back(StrtabBuilder.add(GV.getName()));
4746     Vals.push_back(GV.getName().size());
4747     Vals.push_back(0);
4748     Vals.push_back(0);
4749     Vals.push_back(0);
4750     Vals.push_back(getEncodedLinkage(GV));
4751 
4752     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4753     Vals.clear();
4754   }
4755 
4756   // Emit the function proto information.
4757   for (const Function &F : M) {
4758     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
4759     Vals.push_back(StrtabBuilder.add(F.getName()));
4760     Vals.push_back(F.getName().size());
4761     Vals.push_back(0);
4762     Vals.push_back(0);
4763     Vals.push_back(0);
4764     Vals.push_back(getEncodedLinkage(F));
4765 
4766     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4767     Vals.clear();
4768   }
4769 
4770   // Emit the alias information.
4771   for (const GlobalAlias &A : M.aliases()) {
4772     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4773     Vals.push_back(StrtabBuilder.add(A.getName()));
4774     Vals.push_back(A.getName().size());
4775     Vals.push_back(0);
4776     Vals.push_back(0);
4777     Vals.push_back(0);
4778     Vals.push_back(getEncodedLinkage(A));
4779 
4780     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4781     Vals.clear();
4782   }
4783 
4784   // Emit the ifunc information.
4785   for (const GlobalIFunc &I : M.ifuncs()) {
4786     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4787     Vals.push_back(StrtabBuilder.add(I.getName()));
4788     Vals.push_back(I.getName().size());
4789     Vals.push_back(0);
4790     Vals.push_back(0);
4791     Vals.push_back(0);
4792     Vals.push_back(getEncodedLinkage(I));
4793 
4794     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4795     Vals.clear();
4796   }
4797 }
4798 
4799 void ThinLinkBitcodeWriter::write() {
4800   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4801 
4802   writeModuleVersion();
4803 
4804   writeSimplifiedModuleInfo();
4805 
4806   writePerModuleGlobalValueSummary();
4807 
4808   // Write module hash.
4809   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4810 
4811   Stream.ExitBlock();
4812 }
4813 
4814 void BitcodeWriter::writeThinLinkBitcode(const Module &M,
4815                                          const ModuleSummaryIndex &Index,
4816                                          const ModuleHash &ModHash) {
4817   assert(!WroteStrtab);
4818 
4819   // The Mods vector is used by irsymtab::build, which requires non-const
4820   // Modules in case it needs to materialize metadata. But the bitcode writer
4821   // requires that the module is materialized, so we can cast to non-const here,
4822   // after checking that it is in fact materialized.
4823   assert(M.isMaterialized());
4824   Mods.push_back(const_cast<Module *>(&M));
4825 
4826   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4827                                        ModHash);
4828   ThinLinkWriter.write();
4829 }
4830 
4831 // Write the specified thin link bitcode file to the given raw output stream,
4832 // where it will be written in a new bitcode block. This is used when
4833 // writing the per-module index file for ThinLTO.
4834 void llvm::writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
4835                                       const ModuleSummaryIndex &Index,
4836                                       const ModuleHash &ModHash) {
4837   SmallVector<char, 0> Buffer;
4838   Buffer.reserve(256 * 1024);
4839 
4840   BitcodeWriter Writer(Buffer);
4841   Writer.writeThinLinkBitcode(M, Index, ModHash);
4842   Writer.writeSymtab();
4843   Writer.writeStrtab();
4844 
4845   Out.write((char *)&Buffer.front(), Buffer.size());
4846 }
4847 
4848 static const char *getSectionNameForBitcode(const Triple &T) {
4849   switch (T.getObjectFormat()) {
4850   case Triple::MachO:
4851     return "__LLVM,__bitcode";
4852   case Triple::COFF:
4853   case Triple::ELF:
4854   case Triple::Wasm:
4855   case Triple::UnknownObjectFormat:
4856     return ".llvmbc";
4857   case Triple::GOFF:
4858     llvm_unreachable("GOFF is not yet implemented");
4859     break;
4860   case Triple::XCOFF:
4861     llvm_unreachable("XCOFF is not yet implemented");
4862     break;
4863   }
4864   llvm_unreachable("Unimplemented ObjectFormatType");
4865 }
4866 
4867 static const char *getSectionNameForCommandline(const Triple &T) {
4868   switch (T.getObjectFormat()) {
4869   case Triple::MachO:
4870     return "__LLVM,__cmdline";
4871   case Triple::COFF:
4872   case Triple::ELF:
4873   case Triple::Wasm:
4874   case Triple::UnknownObjectFormat:
4875     return ".llvmcmd";
4876   case Triple::GOFF:
4877     llvm_unreachable("GOFF is not yet implemented");
4878     break;
4879   case Triple::XCOFF:
4880     llvm_unreachable("XCOFF is not yet implemented");
4881     break;
4882   }
4883   llvm_unreachable("Unimplemented ObjectFormatType");
4884 }
4885 
4886 void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
4887                                 bool EmbedBitcode, bool EmbedCmdline,
4888                                 const std::vector<uint8_t> &CmdArgs) {
4889   // Save llvm.compiler.used and remove it.
4890   SmallVector<Constant *, 2> UsedArray;
4891   SmallVector<GlobalValue *, 4> UsedGlobals;
4892   Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
4893   GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
4894   for (auto *GV : UsedGlobals) {
4895     if (GV->getName() != "llvm.embedded.module" &&
4896         GV->getName() != "llvm.cmdline")
4897       UsedArray.push_back(
4898           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4899   }
4900   if (Used)
4901     Used->eraseFromParent();
4902 
4903   // Embed the bitcode for the llvm module.
4904   std::string Data;
4905   ArrayRef<uint8_t> ModuleData;
4906   Triple T(M.getTargetTriple());
4907 
4908   if (EmbedBitcode) {
4909     if (Buf.getBufferSize() == 0 ||
4910         !isBitcode((const unsigned char *)Buf.getBufferStart(),
4911                    (const unsigned char *)Buf.getBufferEnd())) {
4912       // If the input is LLVM Assembly, bitcode is produced by serializing
4913       // the module. Use-lists order need to be preserved in this case.
4914       llvm::raw_string_ostream OS(Data);
4915       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
4916       ModuleData =
4917           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
4918     } else
4919       // If the input is LLVM bitcode, write the input byte stream directly.
4920       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
4921                                      Buf.getBufferSize());
4922   }
4923   llvm::Constant *ModuleConstant =
4924       llvm::ConstantDataArray::get(M.getContext(), ModuleData);
4925   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
4926       M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
4927       ModuleConstant);
4928   GV->setSection(getSectionNameForBitcode(T));
4929   // Set alignment to 1 to prevent padding between two contributions from input
4930   // sections after linking.
4931   GV->setAlignment(Align(1));
4932   UsedArray.push_back(
4933       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4934   if (llvm::GlobalVariable *Old =
4935           M.getGlobalVariable("llvm.embedded.module", true)) {
4936     assert(Old->hasOneUse() &&
4937            "llvm.embedded.module can only be used once in llvm.compiler.used");
4938     GV->takeName(Old);
4939     Old->eraseFromParent();
4940   } else {
4941     GV->setName("llvm.embedded.module");
4942   }
4943 
4944   // Skip if only bitcode needs to be embedded.
4945   if (EmbedCmdline) {
4946     // Embed command-line options.
4947     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CmdArgs.data()),
4948                               CmdArgs.size());
4949     llvm::Constant *CmdConstant =
4950         llvm::ConstantDataArray::get(M.getContext(), CmdData);
4951     GV = new llvm::GlobalVariable(M, CmdConstant->getType(), true,
4952                                   llvm::GlobalValue::PrivateLinkage,
4953                                   CmdConstant);
4954     GV->setSection(getSectionNameForCommandline(T));
4955     GV->setAlignment(Align(1));
4956     UsedArray.push_back(
4957         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
4958     if (llvm::GlobalVariable *Old = M.getGlobalVariable("llvm.cmdline", true)) {
4959       assert(Old->hasOneUse() &&
4960              "llvm.cmdline can only be used once in llvm.compiler.used");
4961       GV->takeName(Old);
4962       Old->eraseFromParent();
4963     } else {
4964       GV->setName("llvm.cmdline");
4965     }
4966   }
4967 
4968   if (UsedArray.empty())
4969     return;
4970 
4971   // Recreate llvm.compiler.used.
4972   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
4973   auto *NewUsed = new GlobalVariable(
4974       M, ATy, false, llvm::GlobalValue::AppendingLinkage,
4975       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
4976   NewUsed->setSection("llvm.metadata");
4977 }
4978