blob: a3bcf6378cbcf68984a64ad2c03c24e8256bdbe4 [file] [log] [blame]
Eugene Zelenko975293f2017-09-07 23:28:24 +00001//===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
Chris Lattnerc1d10d62007-04-22 06:24:45 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
Teresa Johnsonad176792016-11-11 05:34:58 +000014#include "llvm/Bitcode/BitcodeWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "ValueEnumerator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/Triple.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000028#include "llvm/Bitcode/BitCodes.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000029#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000030#include "llvm/Bitcode/LLVMBitCodes.h"
Nico Weber432a3882018-04-30 14:59:11 +000031#include "llvm/Config/llvm-config.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000032#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000034#include "llvm/IR/CallSite.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000035#include "llvm/IR/Comdat.h"
36#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000038#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000039#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000041#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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/InlineAsm.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000048#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000051#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000052#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Module.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000054#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Operator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000056#include "llvm/IR/Type.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000057#include "llvm/IR/UseListOrder.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000058#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/ValueSymbolTable.h"
Peter Collingbournea0f371a2017-04-17 17:51:36 +000060#include "llvm/MC/StringTableBuilder.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000061#include "llvm/Object/IRSymtab.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000062#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"
Torok Edwin56d06592009-07-11 20:10:48 +000067#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000068#include "llvm/Support/MathExtras.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000069#include "llvm/Support/SHA1.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000070#include "llvm/Support/TargetRegistry.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000071#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000072#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000077#include <map>
Eugene Zelenko975293f2017-09-07 23:28:24 +000078#include <memory>
79#include <string>
80#include <utility>
81#include <vector>
82
Chris Lattnerc1d10d62007-04-22 06:24:45 +000083using namespace llvm;
84
Eugene Zelenko975293f2017-09-07 23:28:24 +000085static cl::opt<unsigned>
Mehdi Aminie98f9252016-12-28 22:30:28 +000086 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"));
Eugene Zelenko975293f2017-09-07 23:28:24 +000089
Easwaran Ramanc73cec82018-01-25 19:27:17 +000090cl::opt<bool> WriteRelBFToSummary(
91 "write-relbf-to-summary", cl::Hidden, cl::init(false),
92 cl::desc("Write relative block frequency to function summary "));
Teresa Johnsondb83ace2018-03-31 00:18:08 +000093
94extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
95
Eugene Zelenko975293f2017-09-07 23:28:24 +000096namespace {
97
Chris Lattner4d925982007-05-04 20:52:02 +000098/// These are manifest constants used by the bitcode writer. They do not need to
99/// be kept in sync with the reader, but need to be consistent within this file.
100enum {
Chris Lattner4d925982007-05-04 20:52:02 +0000101 // VALUE_SYMTAB_BLOCK abbrev id's.
102 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +0000103 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +0000104 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000105 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000106
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000107 // CONSTANTS_BLOCK abbrev id's.
108 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
109 CONSTANTS_INTEGER_ABBREV,
110 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +0000111 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000112
Chris Lattnerb80751d2007-05-05 07:44:49 +0000113 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000114 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000115 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +0000116 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000117 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000118 FUNCTION_INST_RET_VOID_ABBREV,
119 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +0000120 FUNCTION_INST_UNREACHABLE_ABBREV,
121 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +0000122};
123
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000124/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000125/// file type.
126class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000127protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000128 /// The stream created and owned by the client.
129 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +0000130
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000131 StringTableBuilder &StrtabBuilder;
132
Teresa Johnson37687f32016-04-23 04:30:47 +0000133public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000134 /// Constructs a BitcodeWriterBase object that writes to the provided
135 /// \p Stream.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000136 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
137 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
Teresa Johnson37687f32016-04-23 04:30:47 +0000138
139protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000140 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000141 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +0000142};
143
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000144void BitcodeWriterBase::writeModuleVersion() {
145 // VERSION: [version#]
146 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
147}
148
Haojie Wang1dec57d2017-07-21 17:25:20 +0000149/// Base class to manage the module bitcode writing, currently subclassed for
150/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
151class ModuleBitcodeWriterBase : public BitcodeWriterBase {
152protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000153 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000154 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000155
156 /// Enumerates ids for all values in the module.
157 ValueEnumerator VE;
158
159 /// Optional per-module index to write for ThinLTO.
160 const ModuleSummaryIndex *Index;
161
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000162 /// Map that holds the correspondence between GUIDs in the summary index,
163 /// that came from indirect call profiles, and a value id generated by this
164 /// class to use in the VST and summary block records.
165 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
166
167 /// Tracks the last value id recorded in the GUIDToValueMap.
168 unsigned GlobalValueId;
169
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000170 /// Saves the offset of the VSTOffset record that must eventually be
171 /// backpatched with the offset of the actual VST.
172 uint64_t VSTOffsetPlaceholder = 0;
173
Teresa Johnson37687f32016-04-23 04:30:47 +0000174public:
Haojie Wang1dec57d2017-07-21 17:25:20 +0000175 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
Teresa Johnson37687f32016-04-23 04:30:47 +0000176 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000177 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000178 BitstreamWriter &Stream,
179 bool ShouldPreserveUseListOrder,
180 const ModuleSummaryIndex *Index)
Rafael Espindola6a86e252018-02-14 19:11:32 +0000181 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
182 VE(M, ShouldPreserveUseListOrder), Index(Index) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000183 // Assign ValueIds to any callee values in the index that came from
184 // indirect call profiles and were recorded as a GUID not a Value*
185 // (which would have been assigned an ID by the ValueEnumerator).
186 // The starting ValueId is just after the number of values in the
187 // ValueEnumerator, so that they can be emitted in the VST.
188 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000189 if (!Index)
190 return;
191 for (const auto &GUIDSummaryLists : *Index)
192 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000193 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000194 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
195 // For each call in the function summary, see if the call
196 // is to a GUID (which means it is for an indirect call,
197 // otherwise we would have a Value for it). If so, synthesize
198 // a value id.
199 for (auto &CallEdge : FS->calls())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000200 if (!CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000201 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000202 }
203
Haojie Wang1dec57d2017-07-21 17:25:20 +0000204protected:
205 void writePerModuleGlobalValueSummary();
206
207private:
208 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
209 GlobalValueSummary *Summary,
210 unsigned ValueID,
211 unsigned FSCallsAbbrev,
212 unsigned FSCallsProfileAbbrev,
213 const Function &F);
214 void writeModuleLevelReferences(const GlobalVariable &V,
215 SmallVector<uint64_t, 64> &NameVals,
216 unsigned FSModRefsAbbrev);
217
218 void assignValueId(GlobalValue::GUID ValGUID) {
219 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
220 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000221
Haojie Wang1dec57d2017-07-21 17:25:20 +0000222 unsigned getValueId(GlobalValue::GUID ValGUID) {
223 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
224 // Expect that any GUID value had a value Id assigned by an
225 // earlier call to assignValueId.
226 assert(VMI != GUIDToValueIdMap.end() &&
227 "GUID does not have assigned value Id");
228 return VMI->second;
229 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000230
Haojie Wang1dec57d2017-07-21 17:25:20 +0000231 // Helper to get the valueId for the type of value recorded in VI.
232 unsigned getValueId(ValueInfo VI) {
233 if (!VI.getValue())
234 return getValueId(VI.getGUID());
235 return VE.getValueID(VI.getValue());
236 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000237
Haojie Wang1dec57d2017-07-21 17:25:20 +0000238 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
239};
240
241/// Class to manage the bitcode writing for a module.
242class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
243 /// Pointer to the buffer allocated by caller for bitcode writing.
244 const SmallVectorImpl<char> &Buffer;
245
246 /// True if a module hash record should be written.
247 bool GenerateHash;
248
249 /// If non-null, when GenerateHash is true, the resulting hash is written
250 /// into ModHash.
251 ModuleHash *ModHash;
252
253 SHA1 Hasher;
254
255 /// The start bit of the identification block.
256 uint64_t BitcodeStartBit;
257
258public:
259 /// Constructs a ModuleBitcodeWriter object for the given Module,
260 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000261 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000262 StringTableBuilder &StrtabBuilder,
263 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
264 const ModuleSummaryIndex *Index, bool GenerateHash,
265 ModuleHash *ModHash = nullptr)
266 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
267 ShouldPreserveUseListOrder, Index),
268 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
269 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
270
Teresa Johnson37687f32016-04-23 04:30:47 +0000271 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000272 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000273
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000274private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000275 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
276
Peter Collingbournec8556152017-07-06 17:56:01 +0000277 size_t addToStrtab(StringRef Str);
278
Teresa Johnson37687f32016-04-23 04:30:47 +0000279 void writeAttributeGroupTable();
280 void writeAttributeTable();
281 void writeTypeTable();
282 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000283 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000284 void writeModuleInfo();
285 void writeValueAsMetadata(const ValueAsMetadata *MD,
286 SmallVectorImpl<uint64_t> &Record);
287 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
288 unsigned Abbrev);
289 unsigned createDILocationAbbrev();
290 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
291 unsigned &Abbrev);
292 unsigned createGenericDINodeAbbrev();
293 void writeGenericDINode(const GenericDINode *N,
294 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
295 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
296 unsigned Abbrev);
297 void writeDIEnumerator(const DIEnumerator *N,
298 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
299 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
300 unsigned Abbrev);
301 void writeDIDerivedType(const DIDerivedType *N,
302 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
303 void writeDICompositeType(const DICompositeType *N,
304 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
305 void writeDISubroutineType(const DISubroutineType *N,
306 SmallVectorImpl<uint64_t> &Record,
307 unsigned Abbrev);
308 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
309 unsigned Abbrev);
310 void writeDICompileUnit(const DICompileUnit *N,
311 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
312 void writeDISubprogram(const DISubprogram *N,
313 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
314 void writeDILexicalBlock(const DILexicalBlock *N,
315 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
317 SmallVectorImpl<uint64_t> &Record,
318 unsigned Abbrev);
319 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
320 unsigned Abbrev);
321 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
322 unsigned Abbrev);
323 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
324 unsigned Abbrev);
325 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
326 unsigned Abbrev);
327 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
328 SmallVectorImpl<uint64_t> &Record,
329 unsigned Abbrev);
330 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
331 SmallVectorImpl<uint64_t> &Record,
332 unsigned Abbrev);
333 void writeDIGlobalVariable(const DIGlobalVariable *N,
334 SmallVectorImpl<uint64_t> &Record,
335 unsigned Abbrev);
336 void writeDILocalVariable(const DILocalVariable *N,
337 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Shiva Chen2c864552018-05-09 02:40:45 +0000338 void writeDILabel(const DILabel *N,
339 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000340 void writeDIExpression(const DIExpression *N,
341 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000342 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
343 SmallVectorImpl<uint64_t> &Record,
344 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000345 void writeDIObjCProperty(const DIObjCProperty *N,
346 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
347 void writeDIImportedEntity(const DIImportedEntity *N,
348 SmallVectorImpl<uint64_t> &Record,
349 unsigned Abbrev);
350 unsigned createNamedMetadataAbbrev();
351 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
352 unsigned createMetadataStringsAbbrev();
353 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
354 SmallVectorImpl<uint64_t> &Record);
355 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000356 SmallVectorImpl<uint64_t> &Record,
357 std::vector<unsigned> *MDAbbrevs = nullptr,
358 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000359 void writeModuleMetadata();
360 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000361 void writeFunctionMetadataAttachment(const Function &F);
362 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
363 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
364 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000365 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000366 void writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000367 void writeSyncScopeNames();
Teresa Johnson37687f32016-04-23 04:30:47 +0000368 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
369 void writeModuleConstants();
370 bool pushValueAndType(const Value *V, unsigned InstID,
371 SmallVectorImpl<unsigned> &Vals);
372 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
373 void pushValue(const Value *V, unsigned InstID,
374 SmallVectorImpl<unsigned> &Vals);
375 void pushValueSigned(const Value *V, unsigned InstID,
376 SmallVectorImpl<uint64_t> &Vals);
377 void writeInstruction(const Instruction &I, unsigned InstID,
378 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000379 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
380 void writeGlobalValueSymbolTable(
381 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000382 void writeUseList(UseListOrder &&Order);
383 void writeUseListBlock(const Function *F);
384 void
385 writeFunction(const Function &F,
386 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
387 void writeBlockInfo();
Teresa Johnson37687f32016-04-23 04:30:47 +0000388 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000389
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000390 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
391 return unsigned(SSID);
392 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000393};
394
395/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000396class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000397 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000398 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000399
Teresa Johnson84174c32016-05-10 13:48:23 +0000400 /// When writing a subset of the index for distributed backends, client
401 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000402 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000403
Teresa Johnson37687f32016-04-23 04:30:47 +0000404 /// Map that holds the correspondence between the GUID used in the combined
405 /// index and a value id generated by this class to use in references.
406 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
407
408 /// Tracks the last value id recorded in the GUIDToValueMap.
409 unsigned GlobalValueId = 0;
410
411public:
412 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000413 /// writing to the provided \p Buffer. When writing a subset of the index
414 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000415 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
416 const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000417 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000418 *ModuleToSummariesForIndex = nullptr)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000419 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000420 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
421 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000422 // in writing out the call graph edges. Save the mapping from GUID
423 // to the new global value id to use when writing those edges, which
424 // are currently saved in the index in terms of GUID.
Teresa Johnson81bbf742017-12-16 00:18:12 +0000425 forEachSummary([&](GVInfo I, bool) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000426 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000427 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000428 }
429
Teresa Johnson84174c32016-05-10 13:48:23 +0000430 /// The below iterator returns the GUID and associated summary.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000431 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
Teresa Johnson84174c32016-05-10 13:48:23 +0000432
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000433 /// Calls the callback for each value GUID and summary to be written to
434 /// bitcode. This hides the details of whether they are being pulled from the
435 /// entire index or just those in a provided ModuleToSummariesForIndex map.
David Blaikie358c0122017-06-02 18:25:29 +0000436 template<typename Functor>
437 void forEachSummary(Functor Callback) {
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000438 if (ModuleToSummariesForIndex) {
439 for (auto &M : *ModuleToSummariesForIndex)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000440 for (auto &Summary : M.second) {
441 Callback(Summary, false);
442 // Ensure aliasee is handled, e.g. for assigning a valueId,
443 // even if we are not importing the aliasee directly (the
444 // imported alias will contain a copy of aliasee).
445 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
446 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
447 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000448 } else {
449 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000450 for (auto &Summary : Summaries.second.SummaryList)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000451 Callback({Summaries.first, Summary.get()}, false);
Teresa Johnson84174c32016-05-10 13:48:23 +0000452 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000453 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000454
Teresa Johnson7a27b132017-06-02 01:56:02 +0000455 /// Calls the callback for each entry in the modulePaths StringMap that
456 /// should be written to the module path string table. This hides the details
457 /// of whether they are being pulled from the entire index or just those in a
458 /// provided ModuleToSummariesForIndex map.
David Blaikieb6b42e02017-06-02 17:24:26 +0000459 template <typename Functor> void forEachModule(Functor Callback) {
Teresa Johnson7a27b132017-06-02 01:56:02 +0000460 if (ModuleToSummariesForIndex) {
461 for (const auto &M : *ModuleToSummariesForIndex) {
462 const auto &MPI = Index.modulePaths().find(M.first);
463 if (MPI == Index.modulePaths().end()) {
464 // This should only happen if the bitcode file was empty, in which
465 // case we shouldn't be importing (the ModuleToSummariesForIndex
466 // would only include the module we are writing and index for).
467 assert(ModuleToSummariesForIndex->size() == 1);
468 continue;
469 }
470 Callback(*MPI);
471 }
472 } else {
473 for (const auto &MPSE : Index.modulePaths())
474 Callback(MPSE);
475 }
476 }
477
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000478 /// Main entry point for writing a combined index to bitcode.
479 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000480
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000481private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000482 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000483 void writeCombinedGlobalValueSummary();
484
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000485 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000486 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000487 if (VMI == GUIDToValueIdMap.end())
488 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000489 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000490 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000491
Teresa Johnson37687f32016-04-23 04:30:47 +0000492 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
493};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000494
Benjamin Kramera65b6102016-05-15 15:18:11 +0000495} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000496
497static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000498 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000499 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000500 case Instruction::Trunc : return bitc::CAST_TRUNC;
501 case Instruction::ZExt : return bitc::CAST_ZEXT;
502 case Instruction::SExt : return bitc::CAST_SEXT;
503 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
504 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
505 case Instruction::UIToFP : return bitc::CAST_UITOFP;
506 case Instruction::SIToFP : return bitc::CAST_SITOFP;
507 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
508 case Instruction::FPExt : return bitc::CAST_FPEXT;
509 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
510 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
511 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000512 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000513 }
514}
515
Teresa Johnson37687f32016-04-23 04:30:47 +0000516static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000517 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000518 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000519 case Instruction::Add:
520 case Instruction::FAdd: return bitc::BINOP_ADD;
521 case Instruction::Sub:
522 case Instruction::FSub: return bitc::BINOP_SUB;
523 case Instruction::Mul:
524 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000525 case Instruction::UDiv: return bitc::BINOP_UDIV;
526 case Instruction::FDiv:
527 case Instruction::SDiv: return bitc::BINOP_SDIV;
528 case Instruction::URem: return bitc::BINOP_UREM;
529 case Instruction::FRem:
530 case Instruction::SRem: return bitc::BINOP_SREM;
531 case Instruction::Shl: return bitc::BINOP_SHL;
532 case Instruction::LShr: return bitc::BINOP_LSHR;
533 case Instruction::AShr: return bitc::BINOP_ASHR;
534 case Instruction::And: return bitc::BINOP_AND;
535 case Instruction::Or: return bitc::BINOP_OR;
536 case Instruction::Xor: return bitc::BINOP_XOR;
537 }
538}
539
Teresa Johnson37687f32016-04-23 04:30:47 +0000540static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000541 switch (Op) {
542 default: llvm_unreachable("Unknown RMW operation!");
543 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
544 case AtomicRMWInst::Add: return bitc::RMW_ADD;
545 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
546 case AtomicRMWInst::And: return bitc::RMW_AND;
547 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
548 case AtomicRMWInst::Or: return bitc::RMW_OR;
549 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
550 case AtomicRMWInst::Max: return bitc::RMW_MAX;
551 case AtomicRMWInst::Min: return bitc::RMW_MIN;
552 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
553 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
554 }
555}
556
Teresa Johnson37687f32016-04-23 04:30:47 +0000557static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000558 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000559 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
560 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
561 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
562 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
563 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
564 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
565 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000566 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000567 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000568}
569
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000570static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
571 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000572 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000573
Chris Lattnere14cb882007-05-04 19:11:41 +0000574 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000575 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
576 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
577 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000578 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000579 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000580
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000581 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000582 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000583}
584
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000585static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
586 switch (Kind) {
587 case Attribute::Alignment:
588 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000589 case Attribute::AllocSize:
590 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000591 case Attribute::AlwaysInline:
592 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000593 case Attribute::ArgMemOnly:
594 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000595 case Attribute::Builtin:
596 return bitc::ATTR_KIND_BUILTIN;
597 case Attribute::ByVal:
598 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000599 case Attribute::Convergent:
600 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000601 case Attribute::InAlloca:
602 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000603 case Attribute::Cold:
604 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000605 case Attribute::InaccessibleMemOnly:
606 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
607 case Attribute::InaccessibleMemOrArgMemOnly:
608 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000609 case Attribute::InlineHint:
610 return bitc::ATTR_KIND_INLINE_HINT;
611 case Attribute::InReg:
612 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000613 case Attribute::JumpTable:
614 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000615 case Attribute::MinSize:
616 return bitc::ATTR_KIND_MIN_SIZE;
617 case Attribute::Naked:
618 return bitc::ATTR_KIND_NAKED;
619 case Attribute::Nest:
620 return bitc::ATTR_KIND_NEST;
621 case Attribute::NoAlias:
622 return bitc::ATTR_KIND_NO_ALIAS;
623 case Attribute::NoBuiltin:
624 return bitc::ATTR_KIND_NO_BUILTIN;
625 case Attribute::NoCapture:
626 return bitc::ATTR_KIND_NO_CAPTURE;
627 case Attribute::NoDuplicate:
628 return bitc::ATTR_KIND_NO_DUPLICATE;
629 case Attribute::NoImplicitFloat:
630 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
631 case Attribute::NoInline:
632 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000633 case Attribute::NoRecurse:
634 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000635 case Attribute::NonLazyBind:
636 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000637 case Attribute::NonNull:
638 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000639 case Attribute::Dereferenceable:
640 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000641 case Attribute::DereferenceableOrNull:
642 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000643 case Attribute::NoRedZone:
644 return bitc::ATTR_KIND_NO_RED_ZONE;
645 case Attribute::NoReturn:
646 return bitc::ATTR_KIND_NO_RETURN;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +0000647 case Attribute::NoCfCheck:
648 return bitc::ATTR_KIND_NOCF_CHECK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000649 case Attribute::NoUnwind:
650 return bitc::ATTR_KIND_NO_UNWIND;
Matt Morehouse236cdaf2018-03-22 17:07:51 +0000651 case Attribute::OptForFuzzing:
652 return bitc::ATTR_KIND_OPT_FOR_FUZZING;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000653 case Attribute::OptimizeForSize:
654 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000655 case Attribute::OptimizeNone:
656 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000657 case Attribute::ReadNone:
658 return bitc::ATTR_KIND_READ_NONE;
659 case Attribute::ReadOnly:
660 return bitc::ATTR_KIND_READ_ONLY;
661 case Attribute::Returned:
662 return bitc::ATTR_KIND_RETURNED;
663 case Attribute::ReturnsTwice:
664 return bitc::ATTR_KIND_RETURNS_TWICE;
665 case Attribute::SExt:
666 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000667 case Attribute::Speculatable:
668 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000669 case Attribute::StackAlignment:
670 return bitc::ATTR_KIND_STACK_ALIGNMENT;
671 case Attribute::StackProtect:
672 return bitc::ATTR_KIND_STACK_PROTECT;
673 case Attribute::StackProtectReq:
674 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
675 case Attribute::StackProtectStrong:
676 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000677 case Attribute::SafeStack:
678 return bitc::ATTR_KIND_SAFESTACK;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +0000679 case Attribute::ShadowCallStack:
680 return bitc::ATTR_KIND_SHADOWCALLSTACK;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +0000681 case Attribute::StrictFP:
682 return bitc::ATTR_KIND_STRICT_FP;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000683 case Attribute::StructRet:
684 return bitc::ATTR_KIND_STRUCT_RET;
685 case Attribute::SanitizeAddress:
686 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +0000687 case Attribute::SanitizeHWAddress:
688 return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000689 case Attribute::SanitizeThread:
690 return bitc::ATTR_KIND_SANITIZE_THREAD;
691 case Attribute::SanitizeMemory:
692 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000693 case Attribute::SwiftError:
694 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000695 case Attribute::SwiftSelf:
696 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000697 case Attribute::UWTable:
698 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000699 case Attribute::WriteOnly:
700 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000701 case Attribute::ZExt:
702 return bitc::ATTR_KIND_Z_EXT;
703 case Attribute::EndAttrKinds:
704 llvm_unreachable("Can not encode end-attribute kinds marker.");
705 case Attribute::None:
706 llvm_unreachable("Can not encode none-attribute.");
707 }
708
709 llvm_unreachable("Trying to encode unknown attribute");
710}
711
Teresa Johnson37687f32016-04-23 04:30:47 +0000712void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000713 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
714 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000715 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000716
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000717 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000718
719 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000720 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
721 unsigned AttrListIndex = Pair.first;
722 AttributeSet AS = Pair.second;
723 Record.push_back(VE.getAttributeGroupID(Pair));
724 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000725
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000726 for (Attribute Attr : AS) {
727 if (Attr.isEnumAttribute()) {
728 Record.push_back(0);
729 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
730 } else if (Attr.isIntAttribute()) {
731 Record.push_back(1);
732 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
733 Record.push_back(Attr.getValueAsInt());
734 } else {
735 StringRef Kind = Attr.getKindAsString();
736 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000737
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000738 Record.push_back(Val.empty() ? 3 : 4);
739 Record.append(Kind.begin(), Kind.end());
740 Record.push_back(0);
741 if (!Val.empty()) {
742 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000743 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000744 }
745 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000746 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000747
748 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
749 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000750 }
751
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000752 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000753}
754
Teresa Johnson37687f32016-04-23 04:30:47 +0000755void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000756 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000757 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000758
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000759 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000760
761 SmallVector<uint64_t, 64> Record;
762 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000763 AttributeList AL = Attrs[i];
764 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
765 AttributeSet AS = AL.getAttributes(i);
766 if (AS.hasAttributes())
767 Record.push_back(VE.getAttributeGroupID({i, AS}));
768 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000769
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000770 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000771 Record.clear();
772 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000773
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000774 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000775}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000776
777/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000778void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000779 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000781 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000782 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000783
David Blaikie7b028102015-02-25 00:51:52 +0000784 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000785
Chris Lattnerccee7062007-05-05 06:30:12 +0000786 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000787 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000788 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000790 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000791 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000792
Chris Lattnerccee7062007-05-05 06:30:12 +0000793 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000794 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000795 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000799 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000800
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000801 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000802 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000803 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000807 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000808
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000809 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000810 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000811 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
812 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
813 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000814 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000815
816 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000817 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000818 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
819 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
820 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000822 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000823
Chris Lattnerccee7062007-05-05 06:30:12 +0000824 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000825 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000826 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
827 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000828 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000829 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000830
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000831 // Emit an entry count so the reader can reserve space.
832 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000833 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000834 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000835
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000836 // Loop over all of the types, emitting each in turn.
837 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000838 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000839 int AbbrevToUse = 0;
840 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000841
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000842 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000843 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
844 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
845 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
846 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
847 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
848 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000849 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000850 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
851 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
852 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000853 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000854 case Type::IntegerTyID:
855 // INTEGER: [width]
856 Code = bitc::TYPE_CODE_INTEGER;
857 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
858 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000859 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000860 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000861 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000862 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000863 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000864 unsigned AddressSpace = PTy->getAddressSpace();
865 TypeVals.push_back(AddressSpace);
866 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000867 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000868 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000869 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000870 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000871 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000872 Code = bitc::TYPE_CODE_FUNCTION;
873 TypeVals.push_back(FT->isVarArg());
874 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000875 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
876 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000877 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000878 break;
879 }
880 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000881 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000882 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000883 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000884 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000885 for (StructType::element_iterator I = ST->element_begin(),
886 E = ST->element_end(); I != E; ++I)
887 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000888
Chris Lattner335d3992011-08-12 18:06:37 +0000889 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000890 Code = bitc::TYPE_CODE_STRUCT_ANON;
891 AbbrevToUse = StructAnonAbbrev;
892 } else {
893 if (ST->isOpaque()) {
894 Code = bitc::TYPE_CODE_OPAQUE;
895 } else {
896 Code = bitc::TYPE_CODE_STRUCT_NAMED;
897 AbbrevToUse = StructNamedAbbrev;
898 }
899
900 // Emit the name if it is present.
901 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000902 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000903 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000904 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000905 break;
906 }
907 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000908 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000909 // ARRAY: [numelts, eltty]
910 Code = bitc::TYPE_CODE_ARRAY;
911 TypeVals.push_back(AT->getNumElements());
912 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000913 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000914 break;
915 }
916 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000917 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000918 // VECTOR [numelts, eltty]
919 Code = bitc::TYPE_CODE_VECTOR;
920 TypeVals.push_back(VT->getNumElements());
921 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
922 break;
923 }
924 }
925
926 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000927 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000928 TypeVals.clear();
929 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000930
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000931 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000932}
933
Teresa Johnson5e22e442016-02-06 16:07:35 +0000934static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
935 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000936 case GlobalValue::ExternalLinkage:
937 return 0;
938 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000939 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000940 case GlobalValue::AppendingLinkage:
941 return 2;
942 case GlobalValue::InternalLinkage:
943 return 3;
944 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000945 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000946 case GlobalValue::ExternalWeakLinkage:
947 return 7;
948 case GlobalValue::CommonLinkage:
949 return 8;
950 case GlobalValue::PrivateLinkage:
951 return 9;
952 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000953 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000954 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000955 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000956 case GlobalValue::AvailableExternallyLinkage:
957 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000958 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000959 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000960}
961
Teresa Johnson5e22e442016-02-06 16:07:35 +0000962static unsigned getEncodedLinkage(const GlobalValue &GV) {
963 return getEncodedLinkage(GV.getLinkage());
964}
965
Charles Saternos75da10d2017-08-04 16:00:58 +0000966static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
967 uint64_t RawFlags = 0;
968 RawFlags |= Flags.ReadNone;
969 RawFlags |= (Flags.ReadOnly << 1);
970 RawFlags |= (Flags.NoRecurse << 2);
971 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
972 return RawFlags;
973}
974
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000975// Decode the flags for GlobalValue in the summary
976static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
977 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000978
Mehdi Amini1380edf2017-02-03 07:41:43 +0000979 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000980 RawFlags |= (Flags.Live << 1);
Sean Fertile4595a912017-11-04 17:04:39 +0000981 RawFlags |= (Flags.DSOLocal << 2);
982
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000983 // Linkage don't need to be remapped at that time for the summary. Any future
984 // change to the getEncodedLinkage() function will need to be taken into
985 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000986 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
987
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000988 return RawFlags;
989}
990
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000991static unsigned getEncodedVisibility(const GlobalValue &GV) {
992 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000993 case GlobalValue::DefaultVisibility: return 0;
994 case GlobalValue::HiddenVisibility: return 1;
995 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000996 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000997 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000998}
999
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001000static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1001 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001002 case GlobalValue::DefaultStorageClass: return 0;
1003 case GlobalValue::DLLImportStorageClass: return 1;
1004 case GlobalValue::DLLExportStorageClass: return 2;
1005 }
1006 llvm_unreachable("Invalid DLL storage class");
1007}
1008
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001009static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001010 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001011 case GlobalVariable::NotThreadLocal: return 0;
1012 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1013 case GlobalVariable::LocalDynamicTLSModel: return 2;
1014 case GlobalVariable::InitialExecTLSModel: return 3;
1015 case GlobalVariable::LocalExecTLSModel: return 4;
1016 }
1017 llvm_unreachable("Invalid TLS model");
1018}
1019
David Majnemerdad0a642014-06-27 18:19:56 +00001020static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1021 switch (C.getSelectionKind()) {
1022 case Comdat::Any:
1023 return bitc::COMDAT_SELECTION_KIND_ANY;
1024 case Comdat::ExactMatch:
1025 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1026 case Comdat::Largest:
1027 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1028 case Comdat::NoDuplicates:
1029 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1030 case Comdat::SameSize:
1031 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1032 }
1033 llvm_unreachable("Invalid selection kind");
1034}
1035
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001036static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1037 switch (GV.getUnnamedAddr()) {
1038 case GlobalValue::UnnamedAddr::None: return 0;
1039 case GlobalValue::UnnamedAddr::Local: return 2;
1040 case GlobalValue::UnnamedAddr::Global: return 1;
1041 }
1042 llvm_unreachable("Invalid unnamed_addr");
1043}
1044
Peter Collingbournec8556152017-07-06 17:56:01 +00001045size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1046 if (GenerateHash)
1047 Hasher.update(Str);
1048 return StrtabBuilder.add(Str);
1049}
1050
Teresa Johnson37687f32016-04-23 04:30:47 +00001051void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +00001052 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +00001053 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001054 // COMDAT: [strtab offset, strtab size, selection_kind]
Peter Collingbournec8556152017-07-06 17:56:01 +00001055 Vals.push_back(addToStrtab(C->getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001056 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +00001057 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001058 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +00001059 Vals.clear();
1060 }
1061}
1062
Teresa Johnsonff642b92015-09-17 20:12:00 +00001063/// Write a record that will eventually hold the word offset of the
1064/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +00001065/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001066void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001067 // Write a placeholder value in for the offset of the real VST,
1068 // which is written after the function blocks so that it can include
1069 // the offset of each function. The placeholder offset will be
1070 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001071 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +00001072 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1073 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1074 // hold the real VST offset. Must use fixed instead of VBR as we don't
1075 // know how many VBR chunks to reserve ahead of time.
1076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001077 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00001078
1079 // Emit the placeholder
1080 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001081 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001082
Teresa Johnson37687f32016-04-23 04:30:47 +00001083 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +00001084 // patched when the real VST is written. We can simply subtract the 32-bit
1085 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001086 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001087}
1088
Teresa Johnsone1164de2016-02-10 21:55:02 +00001089enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1090
1091/// Determine the encoding to use for the given string name and length.
David Blaikieb6b42e02017-06-02 17:24:26 +00001092static StringEncoding getStringEncoding(StringRef Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001093 bool isChar6 = true;
David Blaikieb6b42e02017-06-02 17:24:26 +00001094 for (char C : Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001095 if (isChar6)
David Blaikieb6b42e02017-06-02 17:24:26 +00001096 isChar6 = BitCodeAbbrevOp::isChar6(C);
1097 if ((unsigned char)C & 128)
Teresa Johnsone1164de2016-02-10 21:55:02 +00001098 // don't bother scanning the rest.
1099 return SE_Fixed8;
1100 }
1101 if (isChar6)
1102 return SE_Char6;
David Blaikieb6b42e02017-06-02 17:24:26 +00001103 return SE_Fixed7;
Teresa Johnsone1164de2016-02-10 21:55:02 +00001104}
1105
Teresa Johnsonff642b92015-09-17 20:12:00 +00001106/// Emit top-level description of module, including target triple, inline asm,
1107/// descriptors for global variables, and function prototype info.
1108/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001109void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001110 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001111 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001112 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001113 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001114 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001115 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001116 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001117 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001118 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001119 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001120
Gordon Henriksend930f912008-08-17 18:44:35 +00001121 // Emit information about sections and GC, computing how many there are. Also
1122 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001123 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001124 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001125 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001126 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001127 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001128 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001129 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001130 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001131 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001132 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001133 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001134 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001135 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001136 Entry = SectionMap.size();
1137 }
1138 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001139 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001140 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001141 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1142 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001143 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001144 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001145 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001146 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001147 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001148 Entry = SectionMap.size();
1149 }
1150 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001151 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001152 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001153 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001154 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001155 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1156 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001157 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001158 }
1159 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001160 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001161
Chris Lattner4b00d922007-04-23 16:04:05 +00001162 // Emit abbrev for globals, now that we know # sections and max alignment.
1163 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001164 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001165 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001166 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001167 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001171 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1173 //| explicitType << 1
1174 //| constant
1175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1177 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001178 Abbv->Add(BitCodeAbbrevOp(0));
1179 else {
1180 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001182 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001183 }
1184 if (SectionMap.empty()) // Section.
1185 Abbv->Add(BitCodeAbbrevOp(0));
1186 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001188 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001189 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001190 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001191 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001192
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001193 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001194 // Emit the module's source file name.
1195 {
David Blaikieb6b42e02017-06-02 17:24:26 +00001196 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001197 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1198 if (Bits == SE_Char6)
1199 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1200 else if (Bits == SE_Fixed7)
1201 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1202
1203 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1204 auto Abbv = std::make_shared<BitCodeAbbrev>();
1205 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1206 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1207 Abbv->Add(AbbrevOpToUse);
1208 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1209
1210 for (const auto P : M.getSourceFileName())
1211 Vals.push_back((unsigned char)P);
1212
1213 // Emit the finished record.
1214 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1215 Vals.clear();
1216 }
1217
1218 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001219 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001220 unsigned AbbrevToUse = 0;
1221
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001222 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001223 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001224 // unnamed_addr, externally_initialized, dllstorageclass,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001225 // comdat, attributes, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001226 Vals.push_back(addToStrtab(GV.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001227 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001228 Vals.push_back(VE.getTypeID(GV.getValueType()));
1229 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001230 Vals.push_back(GV.isDeclaration() ? 0 :
1231 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001232 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001233 Vals.push_back(Log2_32(GV.getAlignment())+1);
1234 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1235 if (GV.isThreadLocal() ||
1236 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001237 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1238 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001239 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001240 GV.hasComdat() ||
Sean Fertilec70d28b2017-10-26 15:00:26 +00001241 GV.hasAttributes() ||
1242 GV.isDSOLocal()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001243 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001244 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001245 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001246 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001247 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001248 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001249
1250 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1251 Vals.push_back(VE.getAttributeListID(AL));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001252
1253 Vals.push_back(GV.isDSOLocal());
Chris Lattner4b00d922007-04-23 16:04:05 +00001254 } else {
1255 AbbrevToUse = SimpleGVarAbbrev;
1256 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001257
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001258 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001259 Vals.clear();
1260 }
1261
1262 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001263 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001264 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1265 // linkage, paramattrs, alignment, section, visibility, gc,
1266 // unnamed_addr, prologuedata, dllstorageclass, comdat,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001267 // prefixdata, personalityfn, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001268 Vals.push_back(addToStrtab(F.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001269 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001270 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001271 Vals.push_back(F.getCallingConv());
1272 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001273 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001274 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001275 Vals.push_back(Log2_32(F.getAlignment())+1);
1276 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001277 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001278 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001279 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001280 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1281 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001282 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001283 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001284 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1285 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001286 Vals.push_back(
1287 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001288
Sean Fertilec70d28b2017-10-26 15:00:26 +00001289 Vals.push_back(F.isDSOLocal());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001290 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001291 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001292 Vals.clear();
1293 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001294
Chris Lattner44c17072007-04-26 02:46:40 +00001295 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001296 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001297 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001298 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1299 // DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001300 Vals.push_back(addToStrtab(A.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001301 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001302 Vals.push_back(VE.getTypeID(A.getValueType()));
1303 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001304 Vals.push_back(VE.getValueID(A.getAliasee()));
1305 Vals.push_back(getEncodedLinkage(A));
1306 Vals.push_back(getEncodedVisibility(A));
1307 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001308 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001309 Vals.push_back(getEncodedUnnamedAddr(A));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001310 Vals.push_back(A.isDSOLocal());
1311
Chris Lattner44c17072007-04-26 02:46:40 +00001312 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001313 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001314 Vals.clear();
1315 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001316
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001317 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001318 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001319 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001320 // val#, linkage, visibility, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001321 Vals.push_back(addToStrtab(I.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001322 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001323 Vals.push_back(VE.getTypeID(I.getValueType()));
1324 Vals.push_back(I.getType()->getAddressSpace());
1325 Vals.push_back(VE.getValueID(I.getResolver()));
1326 Vals.push_back(getEncodedLinkage(I));
1327 Vals.push_back(getEncodedVisibility(I));
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001328 Vals.push_back(I.isDSOLocal());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001329 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001330 Vals.clear();
1331 }
1332
Teresa Johnson37687f32016-04-23 04:30:47 +00001333 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001334}
1335
Teresa Johnson37687f32016-04-23 04:30:47 +00001336static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001337 uint64_t Flags = 0;
1338
Sanjay Patelc00017d2014-10-15 17:45:13 +00001339 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001340 if (OBO->hasNoSignedWrap())
1341 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1342 if (OBO->hasNoUnsignedWrap())
1343 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001344 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001345 if (PEO->isExact())
1346 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001347 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Sanjay Patel629c4112017-11-06 16:27:15 +00001348 if (FPMO->hasAllowReassoc())
Steven Wu545d34a2018-02-19 19:22:28 +00001349 Flags |= bitc::AllowReassoc;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001350 if (FPMO->hasNoNaNs())
Steven Wu545d34a2018-02-19 19:22:28 +00001351 Flags |= bitc::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001352 if (FPMO->hasNoInfs())
Steven Wu545d34a2018-02-19 19:22:28 +00001353 Flags |= bitc::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001354 if (FPMO->hasNoSignedZeros())
Steven Wu545d34a2018-02-19 19:22:28 +00001355 Flags |= bitc::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001356 if (FPMO->hasAllowReciprocal())
Steven Wu545d34a2018-02-19 19:22:28 +00001357 Flags |= bitc::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001358 if (FPMO->hasAllowContract())
Steven Wu545d34a2018-02-19 19:22:28 +00001359 Flags |= bitc::AllowContract;
Sanjay Patel629c4112017-11-06 16:27:15 +00001360 if (FPMO->hasApproxFunc())
Steven Wu545d34a2018-02-19 19:22:28 +00001361 Flags |= bitc::ApproxFunc;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001362 }
1363
1364 return Flags;
1365}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001366
Teresa Johnson37687f32016-04-23 04:30:47 +00001367void ModuleBitcodeWriter::writeValueAsMetadata(
1368 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001369 // Mimic an MDNode with a value as one operand.
1370 Value *V = MD->getValue();
1371 Record.push_back(VE.getTypeID(V->getType()));
1372 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001373 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001374 Record.clear();
1375}
1376
Teresa Johnson37687f32016-04-23 04:30:47 +00001377void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1378 SmallVectorImpl<uint64_t> &Record,
1379 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001380 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001381 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001382 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1383 "Unexpected function-local metadata");
1384 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001385 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001386 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1387 : bitc::METADATA_NODE,
1388 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001389 Record.clear();
1390}
Devang Patele059ba6e2009-07-23 01:07:34 +00001391
Teresa Johnson37687f32016-04-23 04:30:47 +00001392unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001393 // Assume the column is usually under 128, and always output the inlined-at
1394 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001395 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001396 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001402 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001403}
1404
Teresa Johnson37687f32016-04-23 04:30:47 +00001405void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1406 SmallVectorImpl<uint64_t> &Record,
1407 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001408 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001409 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001410
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001411 Record.push_back(N->isDistinct());
1412 Record.push_back(N->getLine());
1413 Record.push_back(N->getColumn());
1414 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001415 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001416
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001417 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001418 Record.clear();
1419}
1420
Teresa Johnson37687f32016-04-23 04:30:47 +00001421unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001422 // Assume the column is usually under 128, and always output the inlined-at
1423 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001424 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001425 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1426 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1427 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1428 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1429 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1430 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1431 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001432 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001433}
1434
Teresa Johnson37687f32016-04-23 04:30:47 +00001435void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1436 SmallVectorImpl<uint64_t> &Record,
1437 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001438 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001439 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001440
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001441 Record.push_back(N->isDistinct());
1442 Record.push_back(N->getTag());
1443 Record.push_back(0); // Per-tag version field; unused for now.
1444
1445 for (auto &I : N->operands())
1446 Record.push_back(VE.getMetadataOrNullID(I));
1447
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001448 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001449 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001450}
1451
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001452static uint64_t rotateSign(int64_t I) {
1453 uint64_t U = I;
1454 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001455}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001456
Teresa Johnson37687f32016-04-23 04:30:47 +00001457void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1458 SmallVectorImpl<uint64_t> &Record,
1459 unsigned Abbrev) {
Sander de Smalenfdf40912018-01-24 09:56:07 +00001460 const uint64_t Version = 1 << 1;
1461 Record.push_back((uint64_t)N->isDistinct() | Version);
1462 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001463 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001464
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001465 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001466 Record.clear();
1467}
1468
Teresa Johnson37687f32016-04-23 04:30:47 +00001469void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1470 SmallVectorImpl<uint64_t> &Record,
1471 unsigned Abbrev) {
Momchil Velikov08dc66e2018-02-12 16:10:09 +00001472 Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001473 Record.push_back(rotateSign(N->getValue()));
1474 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1475
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001476 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001477 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001478}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001479
Teresa Johnson37687f32016-04-23 04:30:47 +00001480void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1481 SmallVectorImpl<uint64_t> &Record,
1482 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001483 Record.push_back(N->isDistinct());
1484 Record.push_back(N->getTag());
1485 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1486 Record.push_back(N->getSizeInBits());
1487 Record.push_back(N->getAlignInBits());
1488 Record.push_back(N->getEncoding());
1489
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001490 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001491 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001492}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001493
Teresa Johnson37687f32016-04-23 04:30:47 +00001494void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1495 SmallVectorImpl<uint64_t> &Record,
1496 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001497 Record.push_back(N->isDistinct());
1498 Record.push_back(N->getTag());
1499 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1500 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1501 Record.push_back(N->getLine());
1502 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001503 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001504 Record.push_back(N->getSizeInBits());
1505 Record.push_back(N->getAlignInBits());
1506 Record.push_back(N->getOffsetInBits());
1507 Record.push_back(N->getFlags());
1508 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1509
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001510 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1511 // that there is no DWARF address space associated with DIDerivedType.
1512 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1513 Record.push_back(*DWARFAddressSpace + 1);
1514 else
1515 Record.push_back(0);
1516
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001517 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001518 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001519}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001520
Teresa Johnson37687f32016-04-23 04:30:47 +00001521void ModuleBitcodeWriter::writeDICompositeType(
1522 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1523 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001524 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001525 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001526 Record.push_back(N->getTag());
1527 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1528 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1529 Record.push_back(N->getLine());
1530 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1531 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1532 Record.push_back(N->getSizeInBits());
1533 Record.push_back(N->getAlignInBits());
1534 Record.push_back(N->getOffsetInBits());
1535 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001536 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001537 Record.push_back(N->getRuntimeLang());
1538 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001539 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001540 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
Adrian Prantl8c599212018-02-06 23:45:59 +00001541 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001542
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001543 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001544 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001545}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001546
Teresa Johnson37687f32016-04-23 04:30:47 +00001547void ModuleBitcodeWriter::writeDISubroutineType(
1548 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1549 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001550 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001551 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001552 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001553 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001554 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001555
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001556 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001557 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001558}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001559
Teresa Johnson37687f32016-04-23 04:30:47 +00001560void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1561 SmallVectorImpl<uint64_t> &Record,
1562 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001563 Record.push_back(N->isDistinct());
1564 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1565 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Scott Linder71603842018-02-12 19:45:54 +00001566 if (N->getRawChecksum()) {
1567 Record.push_back(N->getRawChecksum()->Kind);
1568 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1569 } else {
1570 // Maintain backwards compatibility with the old internal representation of
1571 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1572 Record.push_back(0);
1573 Record.push_back(VE.getMetadataOrNullID(nullptr));
1574 }
Scott Linder16c7bda2018-02-23 23:01:06 +00001575 auto Source = N->getRawSource();
1576 if (Source)
1577 Record.push_back(VE.getMetadataOrNullID(*Source));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001578
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001579 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001580 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001581}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001582
Teresa Johnson37687f32016-04-23 04:30:47 +00001583void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1584 SmallVectorImpl<uint64_t> &Record,
1585 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001586 assert(N->isDistinct() && "Expected distinct compile units");
1587 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001588 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001589 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001590 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1591 Record.push_back(N->isOptimized());
1592 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1593 Record.push_back(N->getRuntimeVersion());
1594 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1595 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001596 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1597 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001598 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001599 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1600 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001601 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001602 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001603 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001604 Record.push_back(N->getDebugInfoForProfiling());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001605 Record.push_back(N->getGnuPubnames());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001606
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001607 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001608 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001609}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001610
Teresa Johnson37687f32016-04-23 04:30:47 +00001611void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1612 SmallVectorImpl<uint64_t> &Record,
1613 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001614 uint64_t HasUnitFlag = 1 << 1;
1615 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001616 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1617 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1618 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1619 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1620 Record.push_back(N->getLine());
1621 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1622 Record.push_back(N->isLocalToUnit());
1623 Record.push_back(N->isDefinition());
1624 Record.push_back(N->getScopeLine());
1625 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1626 Record.push_back(N->getVirtuality());
1627 Record.push_back(N->getVirtualIndex());
1628 Record.push_back(N->getFlags());
1629 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001630 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001631 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001632 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Shiva Chen2c864552018-05-09 02:40:45 +00001633 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001634 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001635 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001636
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001637 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001638 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001639}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001640
Teresa Johnson37687f32016-04-23 04:30:47 +00001641void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1642 SmallVectorImpl<uint64_t> &Record,
1643 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001644 Record.push_back(N->isDistinct());
1645 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1646 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1647 Record.push_back(N->getLine());
1648 Record.push_back(N->getColumn());
1649
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001650 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001651 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001652}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001653
Teresa Johnson37687f32016-04-23 04:30:47 +00001654void ModuleBitcodeWriter::writeDILexicalBlockFile(
1655 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1656 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001657 Record.push_back(N->isDistinct());
1658 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1659 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1660 Record.push_back(N->getDiscriminator());
1661
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001662 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001663 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001664}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001665
Teresa Johnson37687f32016-04-23 04:30:47 +00001666void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1667 SmallVectorImpl<uint64_t> &Record,
1668 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001669 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001670 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001671 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001672
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001673 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001674 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001675}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001676
Teresa Johnson37687f32016-04-23 04:30:47 +00001677void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1678 SmallVectorImpl<uint64_t> &Record,
1679 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001680 Record.push_back(N->isDistinct());
1681 Record.push_back(N->getMacinfoType());
1682 Record.push_back(N->getLine());
1683 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1684 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1685
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001686 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001687 Record.clear();
1688}
1689
Teresa Johnson37687f32016-04-23 04:30:47 +00001690void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1691 SmallVectorImpl<uint64_t> &Record,
1692 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001693 Record.push_back(N->isDistinct());
1694 Record.push_back(N->getMacinfoType());
1695 Record.push_back(N->getLine());
1696 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1697 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1698
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001699 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001700 Record.clear();
1701}
1702
Teresa Johnson37687f32016-04-23 04:30:47 +00001703void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1704 SmallVectorImpl<uint64_t> &Record,
1705 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001706 Record.push_back(N->isDistinct());
1707 for (auto &I : N->operands())
1708 Record.push_back(VE.getMetadataOrNullID(I));
1709
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001710 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001711 Record.clear();
1712}
1713
Teresa Johnson37687f32016-04-23 04:30:47 +00001714void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1715 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1716 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001717 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001718 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1719 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1720
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001721 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001722 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001723}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001724
Teresa Johnson37687f32016-04-23 04:30:47 +00001725void ModuleBitcodeWriter::writeDITemplateValueParameter(
1726 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1727 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001728 Record.push_back(N->isDistinct());
1729 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001730 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1731 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1732 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1733
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001734 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001735 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001736}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001737
Teresa Johnson37687f32016-04-23 04:30:47 +00001738void ModuleBitcodeWriter::writeDIGlobalVariable(
1739 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1740 unsigned Abbrev) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001741 const uint64_t Version = 1 << 1;
1742 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001743 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1744 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1745 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1746 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1747 Record.push_back(N->getLine());
1748 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1749 Record.push_back(N->isLocalToUnit());
1750 Record.push_back(N->isDefinition());
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001751 Record.push_back(/* expr */ 0);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001752 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001753 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001754
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001755 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001756 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001757}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001758
Teresa Johnson37687f32016-04-23 04:30:47 +00001759void ModuleBitcodeWriter::writeDILocalVariable(
1760 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1761 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001762 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001763 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001764 // 1) Record has no artificial tag (Record[1]),
1765 // has no obsolete inlinedAt field (Record[9]).
1766 // In this case Record size will be 8, HasAlignment flag is false.
1767 // 2) Record has artificial tag (Record[1]),
1768 // has no obsolete inlignedAt field (Record[9]).
1769 // In this case Record size will be 9, HasAlignment flag is false.
1770 // 3) Record has both artificial tag (Record[1]) and
1771 // obsolete inlignedAt field (Record[9]).
1772 // In this case Record size will be 10, HasAlignment flag is false.
1773 // 4) Record has neither artificial tag, nor inlignedAt field, but
1774 // HasAlignment flag is true and Record[8] contains alignment value.
1775 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001776 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001777 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1778 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1779 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1780 Record.push_back(N->getLine());
1781 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1782 Record.push_back(N->getArg());
1783 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001784 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001785
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001786 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001787 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001788}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001789
Shiva Chen2c864552018-05-09 02:40:45 +00001790void ModuleBitcodeWriter::writeDILabel(
1791 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
1792 unsigned Abbrev) {
1793 Record.push_back((uint64_t)N->isDistinct());
1794 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1795 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1796 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1797 Record.push_back(N->getLine());
1798
1799 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
1800 Record.clear();
1801}
1802
Teresa Johnson37687f32016-04-23 04:30:47 +00001803void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1804 SmallVectorImpl<uint64_t> &Record,
1805 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001806 Record.reserve(N->getElements().size() + 1);
Florian Hahnffc498d2017-06-14 13:14:38 +00001807 const uint64_t Version = 3 << 1;
Adrian Prantl6825fb62017-04-18 01:21:53 +00001808 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001809 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001810
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001811 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001812 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001813}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001814
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001815void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1816 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1817 unsigned Abbrev) {
1818 Record.push_back(N->isDistinct());
1819 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1820 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
Charles Saternos75da10d2017-08-04 16:00:58 +00001821
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001822 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1823 Record.clear();
1824}
1825
Teresa Johnson37687f32016-04-23 04:30:47 +00001826void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1827 SmallVectorImpl<uint64_t> &Record,
1828 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001829 Record.push_back(N->isDistinct());
1830 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1831 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1832 Record.push_back(N->getLine());
1833 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1834 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1835 Record.push_back(N->getAttributes());
1836 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1837
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001838 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001839 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001840}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001841
Teresa Johnson37687f32016-04-23 04:30:47 +00001842void ModuleBitcodeWriter::writeDIImportedEntity(
1843 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1844 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001845 Record.push_back(N->isDistinct());
1846 Record.push_back(N->getTag());
1847 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1848 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1849 Record.push_back(N->getLine());
1850 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Adrian Prantld63bfd22017-07-19 00:09:54 +00001851 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001852
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001853 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001854 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001855}
1856
Teresa Johnson37687f32016-04-23 04:30:47 +00001857unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001858 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001859 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1860 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1861 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001862 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001863}
1864
Teresa Johnson37687f32016-04-23 04:30:47 +00001865void ModuleBitcodeWriter::writeNamedMetadata(
1866 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001867 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001868 return;
1869
Teresa Johnson37687f32016-04-23 04:30:47 +00001870 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001871 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001872 // Write name.
1873 StringRef Str = NMD.getName();
1874 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001875 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001876 Record.clear();
1877
1878 // Write named metadata operands.
1879 for (const MDNode *N : NMD.operands())
1880 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001881 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001882 Record.clear();
1883 }
1884}
1885
Teresa Johnson37687f32016-04-23 04:30:47 +00001886unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001887 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001888 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1889 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001892 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001893}
1894
1895/// Write out a record for MDString.
1896///
1897/// All the metadata strings in a metadata block are emitted in a single
1898/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001899void ModuleBitcodeWriter::writeMetadataStrings(
1900 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001901 if (Strings.empty())
1902 return;
1903
1904 // Start the record with the number of strings.
1905 Record.push_back(bitc::METADATA_STRINGS);
1906 Record.push_back(Strings.size());
1907
1908 // Emit the sizes of the strings in the blob.
1909 SmallString<256> Blob;
1910 {
1911 BitstreamWriter W(Blob);
1912 for (const Metadata *MD : Strings)
1913 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1914 W.FlushToWord();
1915 }
1916
1917 // Add the offset to the strings to the record.
1918 Record.push_back(Blob.size());
1919
1920 // Add the strings to the blob.
1921 for (const Metadata *MD : Strings)
1922 Blob.append(cast<MDString>(MD)->getString());
1923
1924 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001925 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001926 Record.clear();
1927}
1928
Mehdi Aminie98f9252016-12-28 22:30:28 +00001929// Generates an enum to use as an index in the Abbrev array of Metadata record.
1930enum MetadataAbbrev : unsigned {
1931#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1932#include "llvm/IR/Metadata.def"
1933 LastPlusOne
1934};
1935
Teresa Johnson37687f32016-04-23 04:30:47 +00001936void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001937 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1938 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001939 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001940 return;
1941
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001942 // Initialize MDNode abbreviations.
1943#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1944#include "llvm/IR/Metadata.def"
1945
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001946 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001947 if (IndexPos)
1948 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001949 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001950 assert(N->isResolved() && "Expected forward references to be resolved");
1951
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001952 switch (N->getMetadataID()) {
1953 default:
1954 llvm_unreachable("Invalid MDNode subclass");
1955#define HANDLE_MDNODE_LEAF(CLASS) \
1956 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001957 if (MDAbbrevs) \
1958 write##CLASS(cast<CLASS>(N), Record, \
1959 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1960 else \
1961 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001962 continue;
1963#include "llvm/IR/Metadata.def"
1964 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001965 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001966 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001967 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001968}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001969
Teresa Johnson37687f32016-04-23 04:30:47 +00001970void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001971 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001972 return;
1973
Mehdi Aminie98f9252016-12-28 22:30:28 +00001974 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001975 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001976
1977 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1978 // block and load any metadata.
1979 std::vector<unsigned> MDAbbrevs;
1980
1981 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1982 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1983 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1984 createGenericDINodeAbbrev();
1985
David Blaikie7ad9dc12017-01-04 22:36:33 +00001986 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001987 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001990 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001991
David Blaikie7ad9dc12017-01-04 22:36:33 +00001992 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001993 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001996 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001997
1998 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00001999 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00002000
2001 // We only emit an index for the metadata record if we have more than a given
2002 // (naive) threshold of metadatas, otherwise it is not worth it.
2003 if (VE.getNonMDStrings().size() > IndexThreshold) {
2004 // Write a placeholder value in for the offset of the metadata index,
2005 // which is written after the records, so that it can include
2006 // the offset of each entry. The placeholder offset will be
2007 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00002008 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00002009 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2010 }
2011
2012 // Compute and save the bit offset to the current position, which will be
2013 // patched when we emit the index later. We can simply subtract the 64-bit
2014 // fixed size from the current bit number to get the location to backpatch.
2015 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2016
2017 // This index will contain the bitpos for each individual record.
2018 std::vector<uint64_t> IndexPos;
2019 IndexPos.reserve(VE.getNonMDStrings().size());
2020
2021 // Write all the records
2022 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2023
2024 if (VE.getNonMDStrings().size() > IndexThreshold) {
2025 // Now that we have emitted all the records we will emit the index. But
2026 // first
2027 // backpatch the forward reference so that the reader can skip the records
2028 // efficiently.
2029 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2030 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2031
2032 // Delta encode the index.
2033 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2034 for (auto &Elt : IndexPos) {
2035 auto EltDelta = Elt - PreviousValue;
2036 PreviousValue = Elt;
2037 Elt = EltDelta;
2038 }
2039 // Emit the index record.
2040 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2041 IndexPos.clear();
2042 }
2043
2044 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002045 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00002046
2047 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2048 SmallVector<uint64_t, 4> Record;
2049 Record.push_back(VE.getValueID(&GO));
2050 pushGlobalMetadataAttachment(Record, GO);
2051 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2052 };
2053 for (const Function &F : M)
2054 if (F.isDeclaration() && F.hasMetadata())
2055 AddDeclAttachedMetadata(F);
2056 // FIXME: Only store metadata for declarations here, and move data for global
2057 // variable definitions to a separate block (PR28134).
2058 for (const GlobalVariable &GV : M.globals())
2059 if (GV.hasMetadata())
2060 AddDeclAttachedMetadata(GV);
2061
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002062 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002063}
2064
Teresa Johnson37687f32016-04-23 04:30:47 +00002065void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00002066 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002067 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002068
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002069 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002070 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00002071 writeMetadataStrings(VE.getMDStrings(), Record);
2072 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002073 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00002074}
2075
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002076void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2077 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2078 // [n x [id, mdnode]]
2079 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2080 GO.getAllMetadata(MDs);
2081 for (const auto &I : MDs) {
2082 Record.push_back(I.first);
2083 Record.push_back(VE.getMetadataID(I.second));
2084 }
2085}
2086
2087void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002088 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00002089
Devang Patelaf206b82009-09-18 19:26:43 +00002090 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002091
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002092 if (F.hasMetadata()) {
2093 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002094 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002095 Record.clear();
2096 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002097
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002098 // Write metadata attachments
2099 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2100 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002101 for (const BasicBlock &BB : F)
2102 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00002103 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002104 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002105
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002106 // If no metadata, ignore instruction.
2107 if (MDs.empty()) continue;
2108
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002109 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002110
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002111 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2112 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002113 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00002114 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002115 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002116 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00002117 }
2118
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002119 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002120}
2121
Peter Collingbourne21521892016-06-21 23:42:48 +00002122void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00002123 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002124
Devang Patelaf206b82009-09-18 19:26:43 +00002125 // Write metadata kinds
2126 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00002127 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002128 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002129
Dan Gohman43aa8f02010-07-20 21:42:28 +00002130 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00002131
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002132 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002133
Dan Gohman43aa8f02010-07-20 21:42:28 +00002134 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00002135 Record.push_back(MDKindID);
2136 StringRef KName = Names[MDKindID];
2137 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002138
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002139 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00002140 Record.clear();
2141 }
2142
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002143 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002144}
2145
Teresa Johnson37687f32016-04-23 04:30:47 +00002146void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002147 // Write metadata kinds
2148 //
2149 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2150 //
2151 // OPERAND_BUNDLE_TAG - [strchr x N]
2152
2153 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002154 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002155
2156 if (Tags.empty())
2157 return;
2158
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002159 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002160
2161 SmallVector<uint64_t, 64> Record;
2162
2163 for (auto Tag : Tags) {
2164 Record.append(Tag.begin(), Tag.end());
2165
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002166 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002167 Record.clear();
2168 }
2169
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002170 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002171}
2172
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002173void ModuleBitcodeWriter::writeSyncScopeNames() {
2174 SmallVector<StringRef, 8> SSNs;
2175 M.getContext().getSyncScopeNames(SSNs);
2176 if (SSNs.empty())
2177 return;
2178
2179 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2180
2181 SmallVector<uint64_t, 64> Record;
2182 for (auto SSN : SSNs) {
2183 Record.append(SSN.begin(), SSN.end());
2184 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2185 Record.clear();
2186 }
2187
2188 Stream.ExitBlock();
2189}
2190
Jan Wen Voungafaced02012-10-11 20:20:40 +00002191static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2192 if ((int64_t)V >= 0)
2193 Vals.push_back(V << 1);
2194 else
2195 Vals.push_back((-V << 1) | 1);
2196}
2197
Teresa Johnson37687f32016-04-23 04:30:47 +00002198void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2199 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002200 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002201
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002202 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002203
2204 unsigned AggregateAbbrev = 0;
2205 unsigned String8Abbrev = 0;
2206 unsigned CString7Abbrev = 0;
2207 unsigned CString6Abbrev = 0;
2208 // If this is a constant pool for the module, emit module-specific abbrevs.
2209 if (isGlobal) {
2210 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002211 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002212 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002215 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002216
2217 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002218 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002219 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002222 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002223 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002224 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002225 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002228 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002229 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002230 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002231 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002234 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002235 }
2236
Devang Patel8cca7b42009-08-04 05:01:35 +00002237 SmallVector<uint64_t, 64> Record;
2238
2239 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002240 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002241 for (unsigned i = FirstVal; i != LastVal; ++i) {
2242 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002243 // If we need to switch types, do so now.
2244 if (V->getType() != LastTy) {
2245 LastTy = V->getType();
2246 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002247 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2248 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002249 Record.clear();
2250 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002251
Chris Lattner52523562007-04-24 00:16:04 +00002252 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002253 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002254 unsigned(IA->isAlignStack()) << 1 |
2255 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002256
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002257 // Add the asm string.
2258 const std::string &AsmStr = IA->getAsmString();
2259 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002260 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002261
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002262 // Add the constraint string.
2263 const std::string &ConstraintStr = IA->getConstraintString();
2264 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002265 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002266 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002267 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002268 continue;
2269 }
2270 const Constant *C = cast<Constant>(V);
2271 unsigned Code = -1U;
2272 unsigned AbbrevToUse = 0;
2273 if (C->isNullValue()) {
2274 Code = bitc::CST_CODE_NULL;
2275 } else if (isa<UndefValue>(C)) {
2276 Code = bitc::CST_CODE_UNDEF;
2277 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002278 if (IV->getBitWidth() <= 64) {
2279 uint64_t V = IV->getSExtValue();
2280 emitSignedInt64(Record, V);
2281 Code = bitc::CST_CODE_INTEGER;
2282 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2283 } else { // Wide integers, > 64 bits in size.
2284 // We have an arbitrary precision integer value to write whose
2285 // bit width is > 64. However, in canonical unsigned integer
2286 // format it is likely that the high bits are going to be zero.
2287 // So, we only write the number of active words.
2288 unsigned NWords = IV->getValue().getActiveWords();
2289 const uint64_t *RawWords = IV->getValue().getRawData();
2290 for (unsigned i = 0; i != NWords; ++i) {
2291 emitSignedInt64(Record, RawWords[i]);
2292 }
2293 Code = bitc::CST_CODE_WIDE_INTEGER;
2294 }
Chris Lattner52523562007-04-24 00:16:04 +00002295 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2296 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002297 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002298 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002299 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002300 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002301 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002302 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002303 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002304 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002305 Record.push_back((p[1] << 48) | (p[0] >> 16));
2306 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002307 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002308 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002309 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002310 Record.push_back(p[0]);
2311 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002312 } else {
Eugene Zelenko975293f2017-09-07 23:28:24 +00002313 assert(0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002314 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002315 } else if (isa<ConstantDataSequential>(C) &&
2316 cast<ConstantDataSequential>(C)->isString()) {
2317 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2318 // Emit constant strings specially.
2319 unsigned NumElts = Str->getNumElements();
2320 // If this is a null-terminated string, use the denser CSTRING encoding.
2321 if (Str->isCString()) {
2322 Code = bitc::CST_CODE_CSTRING;
2323 --NumElts; // Don't encode the null, which isn't allowed by char6.
2324 } else {
2325 Code = bitc::CST_CODE_STRING;
2326 AbbrevToUse = String8Abbrev;
2327 }
2328 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2329 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2330 for (unsigned i = 0; i != NumElts; ++i) {
2331 unsigned char V = Str->getElementAsInteger(i);
2332 Record.push_back(V);
2333 isCStr7 &= (V & 128) == 0;
2334 if (isCStrChar6)
2335 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2336 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002337
Chris Lattner372dd1e2012-01-30 00:51:16 +00002338 if (isCStrChar6)
2339 AbbrevToUse = CString6Abbrev;
2340 else if (isCStr7)
2341 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002342 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002343 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002344 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002345 Type *EltTy = CDS->getType()->getElementType();
2346 if (isa<IntegerType>(EltTy)) {
2347 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2348 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002349 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002350 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2351 Record.push_back(
2352 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002353 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002354 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002355 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002356 for (const Value *Op : C->operands())
2357 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002358 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002359 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002360 switch (CE->getOpcode()) {
2361 default:
2362 if (Instruction::isCast(CE->getOpcode())) {
2363 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002364 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002365 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2366 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002367 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002368 } else {
2369 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2370 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002371 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002372 Record.push_back(VE.getValueID(C->getOperand(0)));
2373 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002374 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002375 if (Flags != 0)
2376 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002377 }
2378 break;
David Blaikieb9263572015-03-13 21:03:36 +00002379 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002380 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002381 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002382 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002383 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2384 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2385 Record.push_back((*Idx << 1) | GO->isInBounds());
2386 } else if (GO->isInBounds())
2387 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002388 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2389 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2390 Record.push_back(VE.getValueID(C->getOperand(i)));
2391 }
2392 break;
David Blaikieb9263572015-03-13 21:03:36 +00002393 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002394 case Instruction::Select:
2395 Code = bitc::CST_CODE_CE_SELECT;
2396 Record.push_back(VE.getValueID(C->getOperand(0)));
2397 Record.push_back(VE.getValueID(C->getOperand(1)));
2398 Record.push_back(VE.getValueID(C->getOperand(2)));
2399 break;
2400 case Instruction::ExtractElement:
2401 Code = bitc::CST_CODE_CE_EXTRACTELT;
2402 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2403 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002404 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002405 Record.push_back(VE.getValueID(C->getOperand(1)));
2406 break;
2407 case Instruction::InsertElement:
2408 Code = bitc::CST_CODE_CE_INSERTELT;
2409 Record.push_back(VE.getValueID(C->getOperand(0)));
2410 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002411 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002412 Record.push_back(VE.getValueID(C->getOperand(2)));
2413 break;
2414 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002415 // If the return type and argument types are the same, this is a
2416 // standard shufflevector instruction. If the types are different,
2417 // then the shuffle is widening or truncating the input vectors, and
2418 // the argument type must also be encoded.
2419 if (C->getType() == C->getOperand(0)->getType()) {
2420 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2421 } else {
2422 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2423 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2424 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002425 Record.push_back(VE.getValueID(C->getOperand(0)));
2426 Record.push_back(VE.getValueID(C->getOperand(1)));
2427 Record.push_back(VE.getValueID(C->getOperand(2)));
2428 break;
2429 case Instruction::ICmp:
2430 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002431 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002432 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2433 Record.push_back(VE.getValueID(C->getOperand(0)));
2434 Record.push_back(VE.getValueID(C->getOperand(1)));
2435 Record.push_back(CE->getPredicate());
2436 break;
2437 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002438 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002439 Code = bitc::CST_CODE_BLOCKADDRESS;
2440 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2441 Record.push_back(VE.getValueID(BA->getFunction()));
2442 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002443 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002444#ifndef NDEBUG
2445 C->dump();
2446#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002447 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002448 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002449 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002450 Record.clear();
2451 }
2452
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002453 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002454}
2455
Teresa Johnson37687f32016-04-23 04:30:47 +00002456void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002457 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002458
Chris Lattner52523562007-04-24 00:16:04 +00002459 // Find the first constant to emit, which is the first non-globalvalue value.
2460 // We know globalvalues have been emitted by WriteModuleInfo.
2461 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2462 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002463 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002464 return;
2465 }
2466 }
2467}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002468
Teresa Johnson37687f32016-04-23 04:30:47 +00002469/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002470/// many values, because we need to know what type to create for forward
2471/// references. However, most operands are not forward references, so this type
2472/// field is not needed.
2473///
2474/// This function adds V's value ID to Vals. If the value ID is higher than the
2475/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002476/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002477bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2478 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002479 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002480 // Make encoding relative to the InstID.
2481 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002482 if (ValID >= InstID) {
2483 Vals.push_back(VE.getTypeID(V->getType()));
2484 return true;
2485 }
2486 return false;
2487}
2488
Teresa Johnson37687f32016-04-23 04:30:47 +00002489void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2490 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002491 SmallVector<unsigned, 64> Record;
2492 LLVMContext &C = CS.getInstruction()->getContext();
2493
2494 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002495 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002496 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002497
2498 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002499 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002500
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002501 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002502 Record.clear();
2503 }
2504}
2505
Teresa Johnson37687f32016-04-23 04:30:47 +00002506/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002507/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002508void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2509 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002510 unsigned ValID = VE.getValueID(V);
2511 Vals.push_back(InstID - ValID);
2512}
2513
Teresa Johnson37687f32016-04-23 04:30:47 +00002514void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2515 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002516 unsigned ValID = VE.getValueID(V);
2517 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2518 emitSignedInt64(Vals, diff);
2519}
2520
Chris Lattnere6e364c2007-04-26 05:53:54 +00002521/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002522void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2523 unsigned InstID,
2524 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002525 unsigned Code = 0;
2526 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002527 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002528 switch (I.getOpcode()) {
2529 default:
2530 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002531 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002532 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002533 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002534 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002535 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002536 } else {
2537 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002538 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002539 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002540 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002541 pushValue(I.getOperand(1), InstID, Vals);
2542 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2543 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002544 if (Flags != 0) {
2545 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2546 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2547 Vals.push_back(Flags);
2548 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002549 }
2550 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002551
David Blaikieb5b5efd2015-02-25 01:08:52 +00002552 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002553 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002554 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2555 auto &GEPInst = cast<GetElementPtrInst>(I);
2556 Vals.push_back(GEPInst.isInBounds());
2557 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002558 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002559 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002560 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002561 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002562 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002563 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002564 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002565 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002566 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002567 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002568 }
2569 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002570 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002571 pushValueAndType(I.getOperand(0), InstID, Vals);
2572 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002573 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002574 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002575 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002576 }
Chris Lattner0a603252007-05-01 02:13:26 +00002577 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002578 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002579 pushValueAndType(I.getOperand(1), InstID, Vals);
2580 pushValue(I.getOperand(2), InstID, Vals);
2581 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002582 break;
2583 case Instruction::ExtractElement:
2584 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002585 pushValueAndType(I.getOperand(0), InstID, Vals);
2586 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002587 break;
2588 case Instruction::InsertElement:
2589 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002590 pushValueAndType(I.getOperand(0), InstID, Vals);
2591 pushValue(I.getOperand(1), InstID, Vals);
2592 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002593 break;
2594 case Instruction::ShuffleVector:
2595 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002596 pushValueAndType(I.getOperand(0), InstID, Vals);
2597 pushValue(I.getOperand(1), InstID, Vals);
2598 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002599 break;
2600 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002601 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002602 // compare returning Int1Ty or vector of Int1Ty
2603 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002604 pushValueAndType(I.getOperand(0), InstID, Vals);
2605 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002606 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002607 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002608 if (Flags != 0)
2609 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002610 break;
James Molloy88eb5352015-07-10 12:52:00 +00002611 }
Chris Lattner0a603252007-05-01 02:13:26 +00002612
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002613 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002614 {
2615 Code = bitc::FUNC_CODE_INST_RET;
2616 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002617 if (NumOperands == 0)
2618 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2619 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002620 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002621 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2622 } else {
2623 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002624 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002625 }
2626 }
Chris Lattner0a603252007-05-01 02:13:26 +00002627 break;
2628 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002629 {
2630 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002631 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002632 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2633 if (II.isConditional()) {
2634 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002635 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002636 }
Chris Lattner0a603252007-05-01 02:13:26 +00002637 }
2638 break;
2639 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002640 {
2641 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002642 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002643 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002644 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002645 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002646 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002647 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2648 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002649 }
2650 }
Chris Lattner0a603252007-05-01 02:13:26 +00002651 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002652 case Instruction::IndirectBr:
2653 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002654 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002655 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002656 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002657 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002658 Vals.push_back(VE.getValueID(I.getOperand(i)));
2659 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002660
Chris Lattnerb811e952007-05-01 07:03:37 +00002661 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002662 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002663 const Value *Callee = II->getCalledValue();
2664 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002665
2666 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002667 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002668
Chris Lattner0a603252007-05-01 02:13:26 +00002669 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002671 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002672 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002673 Vals.push_back(VE.getValueID(II->getNormalDest()));
2674 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002675 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002676 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002677
Chris Lattner0a603252007-05-01 02:13:26 +00002678 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002679 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002680 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002681
2682 // Emit type/value pairs for varargs params.
2683 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002684 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002685 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002686 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002687 }
2688 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002689 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002690 case Instruction::Resume:
2691 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002692 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002693 break;
David Majnemer654e1302015-07-31 17:58:14 +00002694 case Instruction::CleanupRet: {
2695 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2696 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002697 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002698 if (CRI.hasUnwindDest())
2699 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2700 break;
2701 }
2702 case Instruction::CatchRet: {
2703 Code = bitc::FUNC_CODE_INST_CATCHRET;
2704 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002705 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002706 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2707 break;
2708 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002709 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002710 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002711 const auto &FuncletPad = cast<FuncletPadInst>(I);
2712 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2713 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002714 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002715
2716 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002717 Vals.push_back(NumArgOperands);
2718 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002719 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002720 break;
2721 }
2722 case Instruction::CatchSwitch: {
2723 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2724 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2725
Teresa Johnson37687f32016-04-23 04:30:47 +00002726 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002727
2728 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2729 Vals.push_back(NumHandlers);
2730 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2731 Vals.push_back(VE.getValueID(CatchPadBB));
2732
2733 if (CatchSwitch.hasUnwindDest())
2734 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002735 break;
2736 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002737 case Instruction::Unreachable:
2738 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002739 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002740 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Jay Foad372ad642011-06-20 14:18:48 +00002742 case Instruction::PHI: {
2743 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002744 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002745 // With the newer instruction encoding, forward references could give
2746 // negative valued IDs. This is most common for PHIs, so we use
2747 // signed VBRs.
2748 SmallVector<uint64_t, 128> Vals64;
2749 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002750 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002751 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002752 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002753 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002754 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002755 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002756 Vals64.clear();
2757 return;
Jay Foad372ad642011-06-20 14:18:48 +00002758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002759
Bill Wendlingfae14752011-08-12 20:24:12 +00002760 case Instruction::LandingPad: {
2761 const LandingPadInst &LP = cast<LandingPadInst>(I);
2762 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2763 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002764 Vals.push_back(LP.isCleanup());
2765 Vals.push_back(LP.getNumClauses());
2766 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2767 if (LP.isCatch(I))
2768 Vals.push_back(LandingPadInst::Catch);
2769 else
2770 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002771 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002772 }
2773 break;
2774 }
2775
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002776 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002777 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002778 const AllocaInst &AI = cast<AllocaInst>(I);
2779 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002780 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002781 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002782 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2783 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2784 "not enough bits for maximum alignment");
2785 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2786 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002787 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002788 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002789 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002790 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792
Chris Lattner0a603252007-05-01 02:13:26 +00002793 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002794 if (cast<LoadInst>(I).isAtomic()) {
2795 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002796 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002797 } else {
2798 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002799 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002800 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2801 }
David Blaikie85035652015-02-25 01:07:20 +00002802 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002803 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2804 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002805 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002806 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002807 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002808 }
Chris Lattner0a603252007-05-01 02:13:26 +00002809 break;
2810 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002811 if (cast<StoreInst>(I).isAtomic())
2812 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2813 else
2814 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002815 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2816 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002817 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2818 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002819 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002820 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002821 Vals.push_back(
2822 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002823 }
Chris Lattner0a603252007-05-01 02:13:26 +00002824 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002825 case Instruction::AtomicCmpXchg:
2826 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002827 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2828 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2829 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002830 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002831 Vals.push_back(
2832 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2833 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002834 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002835 Vals.push_back(
2836 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002837 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002838 break;
2839 case Instruction::AtomicRMW:
2840 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002841 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2842 pushValue(I.getOperand(1), InstID, Vals); // val.
2843 Vals.push_back(
2844 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002845 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002846 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2847 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002848 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002849 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002850 case Instruction::Fence:
2851 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002852 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002853 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002854 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002855 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002856 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002857 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002858
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002859 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002860 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002861
Chris Lattnerc44070802011-06-17 18:17:37 +00002862 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002863
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002864 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002865
Teresa Johnson37687f32016-04-23 04:30:47 +00002866 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002867 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2868 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2869 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2870 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002871 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2872 unsigned(Flags != 0) << bitc::CALL_FMF);
2873 if (Flags != 0)
2874 Vals.push_back(Flags);
2875
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002876 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002877 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878
Chris Lattner0a603252007-05-01 02:13:26 +00002879 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002880 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2881 // Check for labels (can happen with asm labels).
2882 if (FTy->getParamType(i)->isLabelTy())
2883 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2884 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002885 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002886 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002887
Chris Lattnerb811e952007-05-01 07:03:37 +00002888 // Emit type/value pairs for varargs params.
2889 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002890 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002891 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002892 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002893 }
2894 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002895 }
Chris Lattner0a603252007-05-01 02:13:26 +00002896 case Instruction::VAArg:
2897 Code = bitc::FUNC_CODE_INST_VAARG;
2898 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002899 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002900 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2901 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002903
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002904 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002905 Vals.clear();
2906}
2907
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002908/// Write a GlobalValue VST to the module. The purpose of this data structure is
2909/// to allow clients to efficiently find the function body.
2910void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2911 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2912 // Get the offset of the VST we are writing, and backpatch it into
2913 // the VST forward declaration record.
2914 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2915 // The BitcodeStartBit was the stream offset of the identification block.
2916 VSTOffset -= bitcodeStartBit();
2917 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2918 // Note that we add 1 here because the offset is relative to one word
2919 // before the start of the identification block, which was historically
2920 // always the start of the regular bitcode header.
2921 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002922
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002923 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002924
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002925 auto Abbv = std::make_shared<BitCodeAbbrev>();
2926 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2927 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2928 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2929 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002930
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002931 for (const Function &F : M) {
2932 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002933
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002934 if (F.isDeclaration())
2935 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002936
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002937 Record[0] = VE.getValueID(&F);
2938
2939 // Save the word offset of the function (from the start of the
2940 // actual bitcode written to the stream).
2941 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2942 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2943 // Note that we add 1 here because the offset is relative to one word
2944 // before the start of the identification block, which was historically
2945 // always the start of the regular bitcode header.
2946 Record[1] = BitcodeIndex / 32 + 1;
2947
2948 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002949 }
2950
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002951 Stream.ExitBlock();
2952}
2953
2954/// Emit names for arguments, instructions and basic blocks in a function.
2955void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2956 const ValueSymbolTable &VST) {
2957 if (VST.empty())
2958 return;
2959
2960 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2961
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002962 // FIXME: Set up the abbrev, we know how many values there are!
2963 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002964 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002965
Yaron Keren001e2e42015-08-10 07:04:29 +00002966 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002967 // Figure out the encoding to use for the name.
David Blaikieb6b42e02017-06-02 17:24:26 +00002968 StringEncoding Bits = getStringEncoding(Name.getKey());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002969
Chris Lattnera0987962007-05-04 21:31:13 +00002970 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002971 NameVals.push_back(VE.getValueID(Name.getValue()));
2972
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002973 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002974 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002975 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002976 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002977 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002978 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002979 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002980 } else {
2981 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002982 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002983 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002984 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002985 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002986 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002987
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002988 for (const auto P : Name.getKey())
2989 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002990
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002991 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002992 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002993 NameVals.clear();
2994 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002995
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002996 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002997}
2998
Teresa Johnson37687f32016-04-23 04:30:47 +00002999void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003000 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3001 unsigned Code;
3002 if (isa<BasicBlock>(Order.V))
3003 Code = bitc::USELIST_CODE_BB;
3004 else
3005 Code = bitc::USELIST_CODE_DEFAULT;
3006
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00003007 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003008 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003009 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003010}
3011
Teresa Johnson37687f32016-04-23 04:30:47 +00003012void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003013 assert(VE.shouldPreserveUseListOrder() &&
3014 "Expected to be preserving use-list order");
3015
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003016 auto hasMore = [&]() {
3017 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3018 };
3019 if (!hasMore())
3020 // Nothing to do.
3021 return;
3022
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003023 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003024 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003025 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003026 VE.UseListOrders.pop_back();
3027 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003028 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003029}
3030
Teresa Johnson403a7872015-10-04 14:33:43 +00003031/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00003032void ModuleBitcodeWriter::writeFunction(
3033 const Function &F,
3034 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00003035 // Save the bitcode index of the start of this function block for recording
3036 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003037 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003038
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003039 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00003040 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003041
3042 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003043
Chris Lattnere6e364c2007-04-26 05:53:54 +00003044 // Emit the number of basic blocks, so the reader can create them ahead of
3045 // time.
3046 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003047 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003048 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003049
Chris Lattnere6e364c2007-04-26 05:53:54 +00003050 // If there are function-local constants, emit them now.
3051 unsigned CstStart, CstEnd;
3052 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00003053 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003054
Victor Hernandez6c730de2010-01-14 01:50:08 +00003055 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00003056 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00003057
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003058 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003059 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003060
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003061 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003062
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003063 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00003064 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003065 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003066 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3067 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003068 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003069
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00003070 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003071 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003072
Chris Lattner07d09ed2010-04-03 02:17:50 +00003073 // If the instruction has metadata, write a metadata attachment later.
3074 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003075
Chris Lattner07d09ed2010-04-03 02:17:50 +00003076 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003077 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003078 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003079 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003080
3081 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00003082 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003083 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003084 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003085 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003086
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003087 Vals.push_back(DL->getLine());
3088 Vals.push_back(DL->getColumn());
3089 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3090 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003091 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003092 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00003093
3094 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003095 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003096
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003097 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003098 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003099 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00003100
Chris Lattner07d09ed2010-04-03 02:17:50 +00003101 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003102 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003103 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003104 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00003105 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003106 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00003107}
3108
Chris Lattner702658c2007-05-04 18:26:27 +00003109// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003110void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00003111 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00003112 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00003113 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00003114 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003115
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003116 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003117 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003118 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3119 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3121 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003122 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003123 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003124 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003125 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003126
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003127 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003128 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003129 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003133 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003134 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003135 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003136 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003137 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003138 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00003139 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003143 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003144 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003145 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00003146 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003147 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003148 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003149 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00003152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003153 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003154 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003155 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003156 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003157
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003158 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003159 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003160 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003162 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003163 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003164 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003165 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003166 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003167
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003168 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003169 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003170 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003172 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003173 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003174 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003175 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003176
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003177 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003178 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003179 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003182 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3184
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003185 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003186 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003187 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003188 }
3189 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003190 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003191 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003192 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003193 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003194 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003196
Chris Lattnerb80751d2007-05-05 07:44:49 +00003197 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198
Chris Lattnerb80751d2007-05-05 07:44:49 +00003199 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003200 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003201 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3204 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003205 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3206 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003207 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003208 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003209 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003210 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003211 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003212 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003213 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3216 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003217 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003218 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003219 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003220 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003221 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003222 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003223 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3226 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Steven Wu545d34a2018-02-19 19:22:28 +00003227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003228 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003229 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003230 llvm_unreachable("Unexpected abbrev ordering!");
3231 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003232 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003233 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003234 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003237 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003238 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003239 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003240 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003241 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003242 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003243
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003244 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003245 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003246 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003247 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003248 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003249 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003250 }
3251 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003252 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003253 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003255 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003256 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003257 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003258 }
3259 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003260 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003261 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003262 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003263 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003264 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003265 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003266 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003267 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003268 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3271 Log2_32_Ceil(VE.getTypes().size() + 1)));
3272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003274 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003275 FUNCTION_INST_GEP_ABBREV)
3276 llvm_unreachable("Unexpected abbrev ordering!");
3277 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003278
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003279 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003280}
3281
Teresa Johnson403a7872015-10-04 14:33:43 +00003282/// Write the module path strings, currently only used when generating
3283/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003284void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003285 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003286
3287 // TODO: See which abbrev sizes we actually need to emit
3288
3289 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003290 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003291 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3292 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3294 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003295 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003296
3297 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003298 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003299 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003303 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003304
3305 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003306 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003307 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003311 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003312
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003313 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003314 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003315 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003321 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003322
3323 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003324 forEachModule(
3325 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
David Blaikieb6b42e02017-06-02 17:24:26 +00003326 StringRef Key = MPSE.getKey();
3327 const auto &Value = MPSE.getValue();
3328 StringEncoding Bits = getStringEncoding(Key);
Teresa Johnson7a27b132017-06-02 01:56:02 +00003329 unsigned AbbrevToUse = Abbrev8Bit;
3330 if (Bits == SE_Char6)
3331 AbbrevToUse = Abbrev6Bit;
3332 else if (Bits == SE_Fixed7)
3333 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003334
David Blaikieb6b42e02017-06-02 17:24:26 +00003335 Vals.push_back(Value.first);
3336 Vals.append(Key.begin(), Key.end());
Teresa Johnson403a7872015-10-04 14:33:43 +00003337
Teresa Johnson7a27b132017-06-02 01:56:02 +00003338 // Emit the finished record.
3339 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003340
Teresa Johnson7a27b132017-06-02 01:56:02 +00003341 // Emit an optional hash for the module now
David Blaikieb6b42e02017-06-02 17:24:26 +00003342 const auto &Hash = Value.second;
3343 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3344 Vals.assign(Hash.begin(), Hash.end());
Teresa Johnson7a27b132017-06-02 01:56:02 +00003345 // Emit the hash record.
3346 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3347 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003348
Teresa Johnson7a27b132017-06-02 01:56:02 +00003349 Vals.clear();
3350 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003351 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003352}
3353
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003354/// Write the function type metadata related records that need to appear before
3355/// a function summary entry (whether per-module or combined).
3356static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3357 FunctionSummary *FS) {
3358 if (!FS->type_tests().empty())
3359 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3360
3361 SmallVector<uint64_t, 64> Record;
3362
3363 auto WriteVFuncIdVec = [&](uint64_t Ty,
3364 ArrayRef<FunctionSummary::VFuncId> VFs) {
3365 if (VFs.empty())
3366 return;
3367 Record.clear();
3368 for (auto &VF : VFs) {
3369 Record.push_back(VF.GUID);
3370 Record.push_back(VF.Offset);
3371 }
3372 Stream.EmitRecord(Ty, Record);
3373 };
3374
3375 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3376 FS->type_test_assume_vcalls());
3377 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3378 FS->type_checked_load_vcalls());
3379
3380 auto WriteConstVCallVec = [&](uint64_t Ty,
3381 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3382 for (auto &VC : VCs) {
3383 Record.clear();
3384 Record.push_back(VC.VFunc.GUID);
3385 Record.push_back(VC.VFunc.Offset);
3386 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3387 Stream.EmitRecord(Ty, Record);
3388 }
3389 };
3390
3391 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3392 FS->type_test_assume_const_vcalls());
3393 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3394 FS->type_checked_load_const_vcalls());
3395}
3396
Vitaly Buka44396fa2018-02-14 22:41:15 +00003397static void writeWholeProgramDevirtResolutionByArg(
3398 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3399 const WholeProgramDevirtResolution::ByArg &ByArg) {
3400 NameVals.push_back(args.size());
3401 NameVals.insert(NameVals.end(), args.begin(), args.end());
3402
3403 NameVals.push_back(ByArg.TheKind);
3404 NameVals.push_back(ByArg.Info);
3405 NameVals.push_back(ByArg.Byte);
3406 NameVals.push_back(ByArg.Bit);
3407}
3408
3409static void writeWholeProgramDevirtResolution(
3410 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3411 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3412 NameVals.push_back(Id);
3413
3414 NameVals.push_back(Wpd.TheKind);
3415 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3416 NameVals.push_back(Wpd.SingleImplName.size());
3417
3418 NameVals.push_back(Wpd.ResByArg.size());
3419 for (auto &A : Wpd.ResByArg)
3420 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3421}
3422
3423static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3424 StringTableBuilder &StrtabBuilder,
3425 const std::string &Id,
3426 const TypeIdSummary &Summary) {
3427 NameVals.push_back(StrtabBuilder.add(Id));
3428 NameVals.push_back(Id.size());
3429
3430 NameVals.push_back(Summary.TTRes.TheKind);
3431 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3432 NameVals.push_back(Summary.TTRes.AlignLog2);
3433 NameVals.push_back(Summary.TTRes.SizeM1);
3434 NameVals.push_back(Summary.TTRes.BitMask);
3435 NameVals.push_back(Summary.TTRes.InlineBits);
3436
3437 for (auto &W : Summary.WPDRes)
3438 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3439 W.second);
3440}
3441
Teresa Johnson403a7872015-10-04 14:33:43 +00003442// Helper to emit a single function summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003443void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003444 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003445 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3446 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003447 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003448
Teresa Johnson28e457b2016-04-24 14:57:11 +00003449 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003450 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003451
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003452 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003453 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003454 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003455 NameVals.push_back(FS->refs().size());
3456
3457 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003458 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003459
Teresa Johnsondb83ace2018-03-31 00:18:08 +00003460 bool HasProfileData =
3461 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003462 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003463 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003464 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003465 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003466 else if (WriteRelBFToSummary)
3467 NameVals.push_back(ECI.second.RelBlockFreq);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003468 }
3469
3470 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3471 unsigned Code =
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003472 (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3473 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3474 : bitc::FS_PERMODULE));
Teresa Johnson403a7872015-10-04 14:33:43 +00003475
3476 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003477 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003478 NameVals.clear();
3479}
3480
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003481// Collect the global value references in the given variable's initializer,
3482// and emit them in a summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003483void ModuleBitcodeWriterBase::writeModuleLevelReferences(
Teresa Johnson37687f32016-04-23 04:30:47 +00003484 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3485 unsigned FSModRefsAbbrev) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00003486 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3487 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003488 // Only declarations should not have a summary (a declaration might however
3489 // have a summary if the def was in module level asm).
3490 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003491 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003492 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003493 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003494 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003495 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003496 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003497
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003498 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003499 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003500 NameVals.push_back(VE.getValueID(RI.getValue()));
3501 // Sort the refs for determinism output, the vector returned by FS->refs() has
3502 // been initialized from a DenseSet.
Mandeep Singh Grang176c3ef2018-04-05 19:27:04 +00003503 llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003504
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003505 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3506 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003507 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003508}
Teresa Johnson403a7872015-10-04 14:33:43 +00003509
Mehdi Amini8fe69362016-04-24 03:18:11 +00003510// Current version for the summary.
3511// This is bumped whenever we introduce changes in the way some record are
3512// interpreted, like flags for instance.
Charles Saternos75da10d2017-08-04 16:00:58 +00003513static const uint64_t INDEX_VERSION = 4;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003514
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003515/// Emit the per-module summary section alongside the rest of
3516/// the module's bitcode.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003517void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
Peter Collingbournee357fbd2017-06-08 23:01:49 +00003518 // By default we compile with ThinLTO if the module has a summary, but the
3519 // client can request full LTO with a module flag.
3520 bool IsThinLTO = true;
3521 if (auto *MD =
3522 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3523 IsThinLTO = MD->getZExtValue();
3524 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3525 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3526 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003527
Mehdi Amini8fe69362016-04-24 03:18:11 +00003528 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3529
Teresa Johnson620c1402016-09-20 23:07:17 +00003530 if (Index->begin() == Index->end()) {
3531 Stream.ExitBlock();
3532 return;
3533 }
3534
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003535 for (const auto &GVI : valueIds()) {
3536 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3537 ArrayRef<uint64_t>{GVI.second, GVI.first});
3538 }
3539
Easwaran Ramanbf38dee2018-01-24 18:15:29 +00003540 // Abbrev for FS_PERMODULE_PROFILE.
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003541 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003542 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3543 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003544 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003546 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003548 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3550 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003551 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003552
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003553 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3554 Abbv = std::make_shared<BitCodeAbbrev>();
3555 if (WriteRelBFToSummary)
3556 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3557 else
3558 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3559 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3560 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3561 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3562 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3563 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3564 // numrefs x valueid, n x (valueid [, rel_block_freq])
3565 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3566 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3567 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3568
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003569 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003570 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003571 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3572 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003573 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003574 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3575 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003576 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003577
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003578 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003579 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003580 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3581 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003584 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003585
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003586 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003587 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003588 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003589 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003590 // Summary emission does not support anonymous functions, they have to
3591 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003592 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003593 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003594
Peter Collingbourne9667b912017-05-04 18:03:25 +00003595 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3596 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003597 // Only declarations should not have a summary (a declaration might
3598 // however have a summary if the def was in module level asm).
3599 assert(F.isDeclaration());
3600 continue;
3601 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003602 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003603 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3604 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003605 }
3606
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003607 // Capture references from GlobalVariable initializers, which are outside
3608 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003609 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003610 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003611
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003612 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003613 auto *Aliasee = A.getBaseObject();
3614 if (!Aliasee->hasName())
3615 // Nameless function don't have an entry in the summary, skip it.
3616 continue;
3617 auto AliasId = VE.getValueID(&A);
3618 auto AliaseeId = VE.getValueID(Aliasee);
3619 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003620 auto *Summary = Index->getGlobalValueSummary(A);
3621 AliasSummary *AS = cast<AliasSummary>(Summary);
3622 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003623 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003624 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003625 NameVals.clear();
3626 }
3627
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003628 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003629}
3630
Teresa Johnson26ab5772016-03-15 00:04:37 +00003631/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003632void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003633 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003634 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003635
Vitaly Buka769134d2018-02-16 23:38:22 +00003636 // Write the index flags.
3637 uint64_t Flags = 0;
3638 if (Index.withGlobalValueDeadStripping())
3639 Flags |= 0x1;
3640 if (Index.skipModuleByDistributedBackend())
3641 Flags |= 0x2;
3642 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
Teresa Johnsonf3681012018-02-07 04:05:59 +00003643
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003644 for (const auto &GVI : valueIds()) {
3645 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3646 ArrayRef<uint64_t>{GVI.second, GVI.first});
3647 }
3648
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003649 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003650 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003651 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003652 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003653 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003654 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003655 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003656 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003658 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3660 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003661 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003662
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003663 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003664 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003665 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003670 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003672 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003673 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3674 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003675 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003676
3677 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003678 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003679 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003682 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003683 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3684 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003685 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003686
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003687 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003688 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003689 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003691 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003692 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003693 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003694 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003695
Teresa Johnson02e98332016-04-27 13:28:35 +00003696 // The aliases are emitted as a post-pass, and will point to the value
3697 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003698 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003699
Teresa Johnson02e98332016-04-27 13:28:35 +00003700 // Save the value id for each summary for alias emission.
3701 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3702
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003703 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003704
3705 // For local linkage, we also emit the original name separately
3706 // immediately after the record.
3707 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3708 if (!GlobalValue::isLocalLinkage(S.linkage()))
3709 return;
3710 NameVals.push_back(S.getOriginalName());
3711 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3712 NameVals.clear();
3713 };
3714
Teresa Johnson81bbf742017-12-16 00:18:12 +00003715 forEachSummary([&](GVInfo I, bool IsAliasee) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003716 GlobalValueSummary *S = I.second;
3717 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003718
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003719 auto ValueId = getValueId(I.first);
3720 assert(ValueId);
3721 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003722
Teresa Johnson81bbf742017-12-16 00:18:12 +00003723 // If this is invoked for an aliasee, we want to record the above
3724 // mapping, but then not emit a summary entry (if the aliasee is
3725 // to be imported, we will invoke this separately with IsAliasee=false).
3726 if (IsAliasee)
3727 return;
3728
Teresa Johnson84174c32016-05-10 13:48:23 +00003729 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3730 // Will process aliases as a post-pass because the reader wants all
3731 // global to be loaded first.
3732 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003733 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003734 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003735
Teresa Johnson84174c32016-05-10 13:48:23 +00003736 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003737 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003738 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3739 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3740 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003741 auto RefValueId = getValueId(RI.getGUID());
3742 if (!RefValueId)
3743 continue;
3744 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003745 }
3746
Teresa Johnson403a7872015-10-04 14:33:43 +00003747 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003748 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3749 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003750 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003751 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003752 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003753 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003754
3755 auto *FS = cast<FunctionSummary>(S);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003756 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003757
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003758 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003759 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3760 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3761 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003762 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003763 // Fill in below
3764 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003765
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003766 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003767 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003768 auto RefValueId = getValueId(RI.getGUID());
3769 if (!RefValueId)
3770 continue;
3771 NameVals.push_back(*RefValueId);
3772 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003773 }
Charles Saternos75da10d2017-08-04 16:00:58 +00003774 NameVals[5] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003775
3776 bool HasProfileData = false;
3777 for (auto &EI : FS->calls()) {
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003778 HasProfileData |=
3779 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003780 if (HasProfileData)
3781 break;
3782 }
3783
3784 for (auto &EI : FS->calls()) {
3785 // If this GUID doesn't have a value id, it doesn't have a function
3786 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003787 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003788 auto CallValueId = getValueId(GUID);
3789 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003790 // For SamplePGO, the indirect call targets for local functions will
3791 // have its original name annotated in profile. We try to find the
3792 // corresponding PGOFuncName as the GUID.
3793 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003794 if (GUID == 0)
3795 continue;
3796 CallValueId = getValueId(GUID);
3797 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003798 continue;
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003799 // The mapping from OriginalId to GUID may return a GUID
Xinliang David Li5a57b842017-08-16 17:33:43 +00003800 // that corresponds to a static variable. Filter it out here.
3801 // This can happen when
3802 // 1) There is a call to a library function which does not have
3803 // a CallValidId;
3804 // 2) There is a static variable with the OriginalGUID identical
3805 // to the GUID of the library function in 1);
3806 // When this happens, the logic for SamplePGO kicks in and
Mandeep Singh Grang1be19e62017-09-15 20:01:43 +00003807 // the static variable in 2) will be found, which needs to be
Xinliang David Li5a57b842017-08-16 17:33:43 +00003808 // filtered out.
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003809 auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3810 if (GVSum &&
3811 GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3812 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +00003813 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003814 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003815 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003816 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003817 }
3818
3819 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3820 unsigned Code =
3821 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3822
3823 // Emit the finished record.
3824 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3825 NameVals.clear();
3826 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003827 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003828
Teresa Johnson28e457b2016-04-24 14:57:11 +00003829 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003830 auto AliasValueId = SummaryToValueIdMap[AS];
3831 assert(AliasValueId);
3832 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003833 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003834 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003835 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3836 assert(AliaseeValueId);
3837 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003838
3839 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003840 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003841 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003842 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003843 }
3844
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003845 if (!Index.cfiFunctionDefs().empty()) {
3846 for (auto &S : Index.cfiFunctionDefs()) {
3847 NameVals.push_back(StrtabBuilder.add(S));
3848 NameVals.push_back(S.size());
3849 }
3850 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3851 NameVals.clear();
3852 }
3853
3854 if (!Index.cfiFunctionDecls().empty()) {
3855 for (auto &S : Index.cfiFunctionDecls()) {
3856 NameVals.push_back(StrtabBuilder.add(S));
3857 NameVals.push_back(S.size());
3858 }
3859 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3860 NameVals.clear();
3861 }
3862
Vitaly Buka44396fa2018-02-14 22:41:15 +00003863 if (!Index.typeIds().empty()) {
3864 for (auto &S : Index.typeIds()) {
3865 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, S.first, S.second);
3866 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
3867 NameVals.clear();
3868 }
3869 }
3870
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003871 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003872}
3873
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003874/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3875/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003876static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003877 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003878
3879 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003880 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003881 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003884 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003885 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003886 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003887
3888 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003889 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003890 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003892 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003893 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003894 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3895 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003896}
3897
Teresa Johnson37687f32016-04-23 04:30:47 +00003898void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003899 // Emit the module's hash.
3900 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003901 if (GenerateHash) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003902 uint32_t Vals[5];
3903 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3904 Buffer.size() - BlockStartPos));
3905 StringRef Hash = Hasher.result();
3906 for (int Pos = 0; Pos < 20; Pos += 4) {
3907 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3908 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003909
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003910 // Emit the finished record.
3911 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3912
3913 if (ModHash)
3914 // Save the written hash value.
3915 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
Haojie Wang1dec57d2017-07-21 17:25:20 +00003916 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003917}
3918
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003919void ModuleBitcodeWriter::write() {
3920 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003921
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003922 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3923 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003924
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003925 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003926
3927 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003928 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003929
Bill Wendlingdc095552013-02-10 23:09:32 +00003930 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003931 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003932
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003933 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003934 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003935
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003936 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003937 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003938
Teresa Johnson37687f32016-04-23 04:30:47 +00003939 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003940
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003941 // Emit top-level description of module, including target triple, inline asm,
3942 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003943 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003944
Devang Patele059ba6e2009-07-23 01:07:34 +00003945 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003946 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003947
Peter Collingbourne21521892016-06-21 23:42:48 +00003948 // Emit metadata kind names.
3949 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003950
Devang Patelaf206b82009-09-18 19:26:43 +00003951 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003952 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003953
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003954 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003955 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003956 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003957
Teresa Johnson37687f32016-04-23 04:30:47 +00003958 writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003959 writeSyncScopeNames();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003960
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003961 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003962 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003963 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003964 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003965 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003966
3967 // Need to write after the above call to WriteFunction which populates
3968 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003969 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003970 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003971
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003972 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003973
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003974 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003975
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003976 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003977}
3978
Teresa Johnson37687f32016-04-23 04:30:47 +00003979static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3980 uint32_t &Position) {
3981 support::endian::write32le(&Buffer[Position], Value);
3982 Position += 4;
3983}
3984
3985/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003986/// header and trailer to make it compatible with the system archiver. To do
3987/// this we emit the following header, and then emit a trailer that pads the
3988/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003989///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003990/// struct bc_header {
3991/// uint32_t Magic; // 0x0B17C0DE
3992/// uint32_t Version; // Version, currently always 0.
3993/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3994/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3995/// uint32_t CPUType; // CPU specifier.
3996/// ... potentially more later ...
3997/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003998static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003999 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00004000 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004001
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004002 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00004003 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4004 // number from /usr/include/mach/machine.h. It is ok to reproduce the
4005 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00004006 enum {
4007 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4008 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004009 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00004010 DARWIN_CPU_TYPE_POWERPC = 18
4011 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004012
Evan Chengcffdcae2011-06-14 01:51:33 +00004013 Triple::ArchType Arch = TT.getArch();
4014 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004015 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00004016 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004017 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00004018 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004019 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00004020 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004021 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00004022 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004023 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004024
Chris Lattnera660f4b2008-07-09 05:14:23 +00004025 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004026 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004027 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004028 unsigned BCOffset = BWH_HeaderSize;
4029 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004030
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004031 // Write the magic and version.
4032 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00004033 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4034 writeInt32ToBuffer(0, Buffer, Position); // Version.
4035 writeInt32ToBuffer(BCOffset, Buffer, Position);
4036 writeInt32ToBuffer(BCSize, Buffer, Position);
4037 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004038
Chris Lattnera660f4b2008-07-09 05:14:23 +00004039 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004040 while (Buffer.size() & 15)
4041 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00004042}
4043
Teresa Johnson403a7872015-10-04 14:33:43 +00004044/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004045static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004046 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004047 Stream.Emit((unsigned)'B', 8);
4048 Stream.Emit((unsigned)'C', 8);
4049 Stream.Emit(0x0, 4);
4050 Stream.Emit(0xC, 4);
4051 Stream.Emit(0xE, 4);
4052 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00004053}
4054
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004055BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4056 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4057 writeBitcodeHeader(*Stream);
4058}
4059
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004060BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4061
4062void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4063 Stream->EnterSubblock(Block, 3);
4064
4065 auto Abbv = std::make_shared<BitCodeAbbrev>();
4066 Abbv->Add(BitCodeAbbrevOp(Record));
4067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4068 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4069
4070 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4071
4072 Stream->ExitBlock();
4073}
4074
Peter Collingbourne92648c22017-06-27 23:50:11 +00004075void BitcodeWriter::writeSymtab() {
4076 assert(!WroteStrtab && !WroteSymtab);
4077
4078 // If any module has module-level inline asm, we will require a registered asm
4079 // parser for the target so that we can create an accurate symbol table for
4080 // the module.
4081 for (Module *M : Mods) {
4082 if (M->getModuleInlineAsm().empty())
4083 continue;
4084
4085 std::string Err;
4086 const Triple TT(M->getTargetTriple());
4087 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4088 if (!T || !T->hasMCAsmParser())
4089 return;
4090 }
4091
4092 WroteSymtab = true;
4093 SmallVector<char, 0> Symtab;
4094 // The irsymtab::build function may be unable to create a symbol table if the
4095 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4096 // table is not required for correctness, but we still want to be able to
4097 // write malformed modules to bitcode files, so swallow the error.
4098 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4099 consumeError(std::move(E));
4100 return;
4101 }
4102
4103 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4104 {Symtab.data(), Symtab.size()});
4105}
4106
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004107void BitcodeWriter::writeStrtab() {
4108 assert(!WroteStrtab);
4109
4110 std::vector<char> Strtab;
4111 StrtabBuilder.finalizeInOrder();
4112 Strtab.resize(StrtabBuilder.getSize());
4113 StrtabBuilder.write((uint8_t *)Strtab.data());
4114
4115 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4116 {Strtab.data(), Strtab.size()});
4117
4118 WroteStrtab = true;
4119}
4120
4121void BitcodeWriter::copyStrtab(StringRef Strtab) {
4122 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4123 WroteStrtab = true;
4124}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004125
Rafael Espindola6a86e252018-02-14 19:11:32 +00004126void BitcodeWriter::writeModule(const Module &M,
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004127 bool ShouldPreserveUseListOrder,
4128 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004129 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbourne92648c22017-06-27 23:50:11 +00004130 assert(!WroteStrtab);
4131
4132 // The Mods vector is used by irsymtab::build, which requires non-const
4133 // Modules in case it needs to materialize metadata. But the bitcode writer
4134 // requires that the module is materialized, so we can cast to non-const here,
4135 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004136 assert(M.isMaterialized());
4137 Mods.push_back(const_cast<Module *>(&M));
Peter Collingbourne92648c22017-06-27 23:50:11 +00004138
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004139 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004140 ShouldPreserveUseListOrder, Index,
4141 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004142 ModuleWriter.write();
4143}
4144
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004145void BitcodeWriter::writeIndex(
4146 const ModuleSummaryIndex *Index,
4147 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4148 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4149 ModuleToSummariesForIndex);
4150 IndexWriter.write();
4151}
4152
Rafael Espindola6a86e252018-02-14 19:11:32 +00004153/// Write the specified module to the specified output stream.
4154void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00004155 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004156 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004157 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00004158 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00004159 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004160
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004161 // If this is darwin or another generic macho target, reserve space for the
4162 // header.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004163 Triple TT(M.getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00004164 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004165 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004166
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004167 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004168 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4169 ModHash);
Peter Collingbourne92648c22017-06-27 23:50:11 +00004170 Writer.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004171 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004172
Akira Hatanaka1235d282016-01-23 16:02:10 +00004173 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00004174 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004175
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004176 // Write the generated bitstream to "Out".
4177 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004178}
Teresa Johnson403a7872015-10-04 14:33:43 +00004179
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004180void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004181 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00004182
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004183 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00004184
4185 // Write the module paths in the combined index.
4186 writeModStrings();
4187
4188 // Write the summary combined index records.
4189 writeCombinedGlobalValueSummary();
4190
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004191 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00004192}
4193
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004194// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00004195// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00004196// writing the combined index file for ThinLTO. When writing a subset of the
4197// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4198void llvm::WriteIndexToFile(
4199 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00004200 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004201 SmallVector<char, 0> Buffer;
4202 Buffer.reserve(256 * 1024);
4203
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004204 BitcodeWriter Writer(Buffer);
4205 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4206 Writer.writeStrtab();
Teresa Johnson403a7872015-10-04 14:33:43 +00004207
4208 Out.write((char *)&Buffer.front(), Buffer.size());
4209}
Haojie Wang1dec57d2017-07-21 17:25:20 +00004210
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00004211namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +00004212
Haojie Wang1dec57d2017-07-21 17:25:20 +00004213/// Class to manage the bitcode writing for a thin link bitcode file.
4214class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4215 /// ModHash is for use in ThinLTO incremental build, generated while writing
4216 /// the module bitcode file.
4217 const ModuleHash *ModHash;
4218
4219public:
Rafael Espindola6a86e252018-02-14 19:11:32 +00004220 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004221 BitstreamWriter &Stream,
4222 const ModuleSummaryIndex &Index,
4223 const ModuleHash &ModHash)
4224 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4225 /*ShouldPreserveUseListOrder=*/false, &Index),
4226 ModHash(&ModHash) {}
4227
4228 void write();
4229
4230private:
4231 void writeSimplifiedModuleInfo();
4232};
Eugene Zelenko975293f2017-09-07 23:28:24 +00004233
4234} // end anonymous namespace
Haojie Wang1dec57d2017-07-21 17:25:20 +00004235
4236// This function writes a simpilified module info for thin link bitcode file.
4237// It only contains the source file name along with the name(the offset and
4238// size in strtab) and linkage for global values. For the global value info
4239// entry, in order to keep linkage at offset 5, there are three zeros used
4240// as padding.
4241void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4242 SmallVector<unsigned, 64> Vals;
4243 // Emit the module's source file name.
4244 {
4245 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4246 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4247 if (Bits == SE_Char6)
4248 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4249 else if (Bits == SE_Fixed7)
4250 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4251
4252 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4253 auto Abbv = std::make_shared<BitCodeAbbrev>();
4254 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4256 Abbv->Add(AbbrevOpToUse);
4257 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4258
4259 for (const auto P : M.getSourceFileName())
4260 Vals.push_back((unsigned char)P);
4261
4262 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4263 Vals.clear();
4264 }
4265
4266 // Emit the global variable information.
4267 for (const GlobalVariable &GV : M.globals()) {
4268 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4269 Vals.push_back(StrtabBuilder.add(GV.getName()));
4270 Vals.push_back(GV.getName().size());
4271 Vals.push_back(0);
4272 Vals.push_back(0);
4273 Vals.push_back(0);
4274 Vals.push_back(getEncodedLinkage(GV));
4275
4276 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4277 Vals.clear();
4278 }
4279
4280 // Emit the function proto information.
4281 for (const Function &F : M) {
4282 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4283 Vals.push_back(StrtabBuilder.add(F.getName()));
4284 Vals.push_back(F.getName().size());
4285 Vals.push_back(0);
4286 Vals.push_back(0);
4287 Vals.push_back(0);
4288 Vals.push_back(getEncodedLinkage(F));
4289
4290 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4291 Vals.clear();
4292 }
4293
4294 // Emit the alias information.
4295 for (const GlobalAlias &A : M.aliases()) {
4296 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4297 Vals.push_back(StrtabBuilder.add(A.getName()));
4298 Vals.push_back(A.getName().size());
4299 Vals.push_back(0);
4300 Vals.push_back(0);
4301 Vals.push_back(0);
4302 Vals.push_back(getEncodedLinkage(A));
4303
4304 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4305 Vals.clear();
4306 }
4307
4308 // Emit the ifunc information.
4309 for (const GlobalIFunc &I : M.ifuncs()) {
4310 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4311 Vals.push_back(StrtabBuilder.add(I.getName()));
4312 Vals.push_back(I.getName().size());
4313 Vals.push_back(0);
4314 Vals.push_back(0);
4315 Vals.push_back(0);
4316 Vals.push_back(getEncodedLinkage(I));
4317
4318 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4319 Vals.clear();
4320 }
4321}
4322
4323void ThinLinkBitcodeWriter::write() {
4324 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4325
4326 writeModuleVersion();
4327
4328 writeSimplifiedModuleInfo();
4329
4330 writePerModuleGlobalValueSummary();
4331
4332 // Write module hash.
4333 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4334
4335 Stream.ExitBlock();
4336}
4337
Rafael Espindola6a86e252018-02-14 19:11:32 +00004338void BitcodeWriter::writeThinLinkBitcode(const Module &M,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004339 const ModuleSummaryIndex &Index,
4340 const ModuleHash &ModHash) {
4341 assert(!WroteStrtab);
4342
4343 // The Mods vector is used by irsymtab::build, which requires non-const
4344 // Modules in case it needs to materialize metadata. But the bitcode writer
4345 // requires that the module is materialized, so we can cast to non-const here,
4346 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004347 assert(M.isMaterialized());
4348 Mods.push_back(const_cast<Module *>(&M));
Haojie Wang1dec57d2017-07-21 17:25:20 +00004349
4350 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4351 ModHash);
4352 ThinLinkWriter.write();
4353}
4354
4355// Write the specified thin link bitcode file to the given raw output stream,
4356// where it will be written in a new bitcode block. This is used when
4357// writing the per-module index file for ThinLTO.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004358void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004359 const ModuleSummaryIndex &Index,
4360 const ModuleHash &ModHash) {
4361 SmallVector<char, 0> Buffer;
4362 Buffer.reserve(256 * 1024);
4363
4364 BitcodeWriter Writer(Buffer);
4365 Writer.writeThinLinkBitcode(M, Index, ModHash);
4366 Writer.writeSymtab();
4367 Writer.writeStrtab();
4368
4369 Out.write((char *)&Buffer.front(), Buffer.size());
4370}