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