blob: 0738b907be35987c601f362079a0db661462a4fe [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"
Eugene Zelenko975293f2017-09-07 23:28:24 +000031#include "llvm/IR/Attributes.h"
32#include "llvm/IR/BasicBlock.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000033#include "llvm/IR/CallSite.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000034#include "llvm/IR/Comdat.h"
35#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000037#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000038#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000040#include "llvm/IR/Function.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalIFunc.h"
43#include "llvm/IR/GlobalObject.h"
44#include "llvm/IR/GlobalValue.h"
45#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/InlineAsm.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000047#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000050#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000051#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Module.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000053#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/Operator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000055#include "llvm/IR/Type.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000056#include "llvm/IR/UseListOrder.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000057#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/ValueSymbolTable.h"
Peter Collingbournea0f371a2017-04-17 17:51:36 +000059#include "llvm/MC/StringTableBuilder.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000060#include "llvm/Object/IRSymtab.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000061#include "llvm/Support/AtomicOrdering.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Endian.h"
65#include "llvm/Support/Error.h"
Torok Edwin56d06592009-07-11 20:10:48 +000066#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000067#include "llvm/Support/MathExtras.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000068#include "llvm/Support/SHA1.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000069#include "llvm/Support/TargetRegistry.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000070#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000071#include <algorithm>
72#include <cassert>
73#include <cstddef>
74#include <cstdint>
75#include <iterator>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000076#include <map>
Eugene Zelenko975293f2017-09-07 23:28:24 +000077#include <memory>
78#include <string>
79#include <utility>
80#include <vector>
81
Chris Lattnerc1d10d62007-04-22 06:24:45 +000082using namespace llvm;
83
Eugene Zelenko975293f2017-09-07 23:28:24 +000084static cl::opt<unsigned>
Mehdi Aminie98f9252016-12-28 22:30:28 +000085 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
86 cl::desc("Number of metadatas above which we emit an index "
87 "to enable lazy-loading"));
Eugene Zelenko975293f2017-09-07 23:28:24 +000088
Easwaran Ramanc73cec82018-01-25 19:27:17 +000089cl::opt<bool> WriteRelBFToSummary(
90 "write-relbf-to-summary", cl::Hidden, cl::init(false),
91 cl::desc("Write relative block frequency to function summary "));
Eugene Zelenko975293f2017-09-07 23:28:24 +000092namespace {
93
Chris Lattner4d925982007-05-04 20:52:02 +000094/// These are manifest constants used by the bitcode writer. They do not need to
95/// be kept in sync with the reader, but need to be consistent within this file.
96enum {
Chris Lattner4d925982007-05-04 20:52:02 +000097 // VALUE_SYMTAB_BLOCK abbrev id's.
98 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +000099 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +0000100 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000101 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000102
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000103 // CONSTANTS_BLOCK abbrev id's.
104 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
105 CONSTANTS_INTEGER_ABBREV,
106 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +0000107 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000108
Chris Lattnerb80751d2007-05-05 07:44:49 +0000109 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000110 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000111 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +0000112 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000113 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000114 FUNCTION_INST_RET_VOID_ABBREV,
115 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +0000116 FUNCTION_INST_UNREACHABLE_ABBREV,
117 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +0000118};
119
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000120/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000121/// file type.
122class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000123protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000124 /// The stream created and owned by the client.
125 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +0000126
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000127 StringTableBuilder &StrtabBuilder;
128
Teresa Johnson37687f32016-04-23 04:30:47 +0000129public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000130 /// Constructs a BitcodeWriterBase object that writes to the provided
131 /// \p Stream.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000132 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
133 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
Teresa Johnson37687f32016-04-23 04:30:47 +0000134
135protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000136 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000137 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +0000138};
139
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000140void BitcodeWriterBase::writeModuleVersion() {
141 // VERSION: [version#]
142 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
143}
144
Haojie Wang1dec57d2017-07-21 17:25:20 +0000145/// Base class to manage the module bitcode writing, currently subclassed for
146/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
147class ModuleBitcodeWriterBase : public BitcodeWriterBase {
148protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000149 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000150 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000151
152 /// Enumerates ids for all values in the module.
153 ValueEnumerator VE;
154
155 /// Optional per-module index to write for ThinLTO.
156 const ModuleSummaryIndex *Index;
157
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000158 /// Map that holds the correspondence between GUIDs in the summary index,
159 /// that came from indirect call profiles, and a value id generated by this
160 /// class to use in the VST and summary block records.
161 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
162
163 /// Tracks the last value id recorded in the GUIDToValueMap.
164 unsigned GlobalValueId;
165
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000166 /// Saves the offset of the VSTOffset record that must eventually be
167 /// backpatched with the offset of the actual VST.
168 uint64_t VSTOffsetPlaceholder = 0;
169
Teresa Johnson37687f32016-04-23 04:30:47 +0000170public:
Haojie Wang1dec57d2017-07-21 17:25:20 +0000171 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
Teresa Johnson37687f32016-04-23 04:30:47 +0000172 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000173 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000174 BitstreamWriter &Stream,
175 bool ShouldPreserveUseListOrder,
176 const ModuleSummaryIndex *Index)
Rafael Espindola6a86e252018-02-14 19:11:32 +0000177 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
178 VE(M, ShouldPreserveUseListOrder), Index(Index) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000179 // Assign ValueIds to any callee values in the index that came from
180 // indirect call profiles and were recorded as a GUID not a Value*
181 // (which would have been assigned an ID by the ValueEnumerator).
182 // The starting ValueId is just after the number of values in the
183 // ValueEnumerator, so that they can be emitted in the VST.
184 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000185 if (!Index)
186 return;
187 for (const auto &GUIDSummaryLists : *Index)
188 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000189 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000190 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
191 // For each call in the function summary, see if the call
192 // is to a GUID (which means it is for an indirect call,
193 // otherwise we would have a Value for it). If so, synthesize
194 // a value id.
195 for (auto &CallEdge : FS->calls())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000196 if (!CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000197 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000198 }
199
Haojie Wang1dec57d2017-07-21 17:25:20 +0000200protected:
201 void writePerModuleGlobalValueSummary();
202
203private:
204 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
205 GlobalValueSummary *Summary,
206 unsigned ValueID,
207 unsigned FSCallsAbbrev,
208 unsigned FSCallsProfileAbbrev,
209 const Function &F);
210 void writeModuleLevelReferences(const GlobalVariable &V,
211 SmallVector<uint64_t, 64> &NameVals,
212 unsigned FSModRefsAbbrev);
213
214 void assignValueId(GlobalValue::GUID ValGUID) {
215 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
216 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000217
Haojie Wang1dec57d2017-07-21 17:25:20 +0000218 unsigned getValueId(GlobalValue::GUID ValGUID) {
219 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
220 // Expect that any GUID value had a value Id assigned by an
221 // earlier call to assignValueId.
222 assert(VMI != GUIDToValueIdMap.end() &&
223 "GUID does not have assigned value Id");
224 return VMI->second;
225 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000226
Haojie Wang1dec57d2017-07-21 17:25:20 +0000227 // Helper to get the valueId for the type of value recorded in VI.
228 unsigned getValueId(ValueInfo VI) {
229 if (!VI.getValue())
230 return getValueId(VI.getGUID());
231 return VE.getValueID(VI.getValue());
232 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000233
Haojie Wang1dec57d2017-07-21 17:25:20 +0000234 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
235};
236
237/// Class to manage the bitcode writing for a module.
238class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
239 /// Pointer to the buffer allocated by caller for bitcode writing.
240 const SmallVectorImpl<char> &Buffer;
241
242 /// True if a module hash record should be written.
243 bool GenerateHash;
244
245 /// If non-null, when GenerateHash is true, the resulting hash is written
246 /// into ModHash.
247 ModuleHash *ModHash;
248
249 SHA1 Hasher;
250
251 /// The start bit of the identification block.
252 uint64_t BitcodeStartBit;
253
254public:
255 /// Constructs a ModuleBitcodeWriter object for the given Module,
256 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000257 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000258 StringTableBuilder &StrtabBuilder,
259 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
260 const ModuleSummaryIndex *Index, bool GenerateHash,
261 ModuleHash *ModHash = nullptr)
262 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
263 ShouldPreserveUseListOrder, Index),
264 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
265 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
266
Teresa Johnson37687f32016-04-23 04:30:47 +0000267 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000268 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000269
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000270private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000271 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
272
Peter Collingbournec8556152017-07-06 17:56:01 +0000273 size_t addToStrtab(StringRef Str);
274
Teresa Johnson37687f32016-04-23 04:30:47 +0000275 void writeAttributeGroupTable();
276 void writeAttributeTable();
277 void writeTypeTable();
278 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000279 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000280 void writeModuleInfo();
281 void writeValueAsMetadata(const ValueAsMetadata *MD,
282 SmallVectorImpl<uint64_t> &Record);
283 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
284 unsigned Abbrev);
285 unsigned createDILocationAbbrev();
286 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
287 unsigned &Abbrev);
288 unsigned createGenericDINodeAbbrev();
289 void writeGenericDINode(const GenericDINode *N,
290 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
291 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
292 unsigned Abbrev);
293 void writeDIEnumerator(const DIEnumerator *N,
294 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
295 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
296 unsigned Abbrev);
297 void writeDIDerivedType(const DIDerivedType *N,
298 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
299 void writeDICompositeType(const DICompositeType *N,
300 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
301 void writeDISubroutineType(const DISubroutineType *N,
302 SmallVectorImpl<uint64_t> &Record,
303 unsigned Abbrev);
304 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
305 unsigned Abbrev);
306 void writeDICompileUnit(const DICompileUnit *N,
307 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
308 void writeDISubprogram(const DISubprogram *N,
309 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
310 void writeDILexicalBlock(const DILexicalBlock *N,
311 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
312 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
313 SmallVectorImpl<uint64_t> &Record,
314 unsigned Abbrev);
315 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
316 unsigned Abbrev);
317 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
318 unsigned Abbrev);
319 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
320 unsigned Abbrev);
321 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
322 unsigned Abbrev);
323 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
324 SmallVectorImpl<uint64_t> &Record,
325 unsigned Abbrev);
326 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
327 SmallVectorImpl<uint64_t> &Record,
328 unsigned Abbrev);
329 void writeDIGlobalVariable(const DIGlobalVariable *N,
330 SmallVectorImpl<uint64_t> &Record,
331 unsigned Abbrev);
332 void writeDILocalVariable(const DILocalVariable *N,
333 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
334 void writeDIExpression(const DIExpression *N,
335 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000336 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
337 SmallVectorImpl<uint64_t> &Record,
338 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000339 void writeDIObjCProperty(const DIObjCProperty *N,
340 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
341 void writeDIImportedEntity(const DIImportedEntity *N,
342 SmallVectorImpl<uint64_t> &Record,
343 unsigned Abbrev);
344 unsigned createNamedMetadataAbbrev();
345 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
346 unsigned createMetadataStringsAbbrev();
347 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
348 SmallVectorImpl<uint64_t> &Record);
349 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000350 SmallVectorImpl<uint64_t> &Record,
351 std::vector<unsigned> *MDAbbrevs = nullptr,
352 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000353 void writeModuleMetadata();
354 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000355 void writeFunctionMetadataAttachment(const Function &F);
356 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
357 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
358 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000359 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000360 void writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000361 void writeSyncScopeNames();
Teresa Johnson37687f32016-04-23 04:30:47 +0000362 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
363 void writeModuleConstants();
364 bool pushValueAndType(const Value *V, unsigned InstID,
365 SmallVectorImpl<unsigned> &Vals);
366 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
367 void pushValue(const Value *V, unsigned InstID,
368 SmallVectorImpl<unsigned> &Vals);
369 void pushValueSigned(const Value *V, unsigned InstID,
370 SmallVectorImpl<uint64_t> &Vals);
371 void writeInstruction(const Instruction &I, unsigned InstID,
372 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000373 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
374 void writeGlobalValueSymbolTable(
375 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000376 void writeUseList(UseListOrder &&Order);
377 void writeUseListBlock(const Function *F);
378 void
379 writeFunction(const Function &F,
380 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
381 void writeBlockInfo();
Teresa Johnson37687f32016-04-23 04:30:47 +0000382 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000383
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000384 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
385 return unsigned(SSID);
386 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000387};
388
389/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000390class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000391 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000392 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000393
Teresa Johnson84174c32016-05-10 13:48:23 +0000394 /// When writing a subset of the index for distributed backends, client
395 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000396 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000397
Teresa Johnson37687f32016-04-23 04:30:47 +0000398 /// Map that holds the correspondence between the GUID used in the combined
399 /// index and a value id generated by this class to use in references.
400 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
401
402 /// Tracks the last value id recorded in the GUIDToValueMap.
403 unsigned GlobalValueId = 0;
404
405public:
406 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000407 /// writing to the provided \p Buffer. When writing a subset of the index
408 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000409 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
410 const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000411 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000412 *ModuleToSummariesForIndex = nullptr)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000413 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000414 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
415 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000416 // in writing out the call graph edges. Save the mapping from GUID
417 // to the new global value id to use when writing those edges, which
418 // are currently saved in the index in terms of GUID.
Teresa Johnson81bbf742017-12-16 00:18:12 +0000419 forEachSummary([&](GVInfo I, bool) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000420 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000421 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000422 }
423
Teresa Johnson84174c32016-05-10 13:48:23 +0000424 /// The below iterator returns the GUID and associated summary.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000425 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
Teresa Johnson84174c32016-05-10 13:48:23 +0000426
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000427 /// Calls the callback for each value GUID and summary to be written to
428 /// bitcode. This hides the details of whether they are being pulled from the
429 /// entire index or just those in a provided ModuleToSummariesForIndex map.
David Blaikie358c0122017-06-02 18:25:29 +0000430 template<typename Functor>
431 void forEachSummary(Functor Callback) {
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000432 if (ModuleToSummariesForIndex) {
433 for (auto &M : *ModuleToSummariesForIndex)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000434 for (auto &Summary : M.second) {
435 Callback(Summary, false);
436 // Ensure aliasee is handled, e.g. for assigning a valueId,
437 // even if we are not importing the aliasee directly (the
438 // imported alias will contain a copy of aliasee).
439 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
440 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
441 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000442 } else {
443 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000444 for (auto &Summary : Summaries.second.SummaryList)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000445 Callback({Summaries.first, Summary.get()}, false);
Teresa Johnson84174c32016-05-10 13:48:23 +0000446 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000447 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000448
Teresa Johnson7a27b132017-06-02 01:56:02 +0000449 /// Calls the callback for each entry in the modulePaths StringMap that
450 /// should be written to the module path string table. This hides the details
451 /// of whether they are being pulled from the entire index or just those in a
452 /// provided ModuleToSummariesForIndex map.
David Blaikieb6b42e02017-06-02 17:24:26 +0000453 template <typename Functor> void forEachModule(Functor Callback) {
Teresa Johnson7a27b132017-06-02 01:56:02 +0000454 if (ModuleToSummariesForIndex) {
455 for (const auto &M : *ModuleToSummariesForIndex) {
456 const auto &MPI = Index.modulePaths().find(M.first);
457 if (MPI == Index.modulePaths().end()) {
458 // This should only happen if the bitcode file was empty, in which
459 // case we shouldn't be importing (the ModuleToSummariesForIndex
460 // would only include the module we are writing and index for).
461 assert(ModuleToSummariesForIndex->size() == 1);
462 continue;
463 }
464 Callback(*MPI);
465 }
466 } else {
467 for (const auto &MPSE : Index.modulePaths())
468 Callback(MPSE);
469 }
470 }
471
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000472 /// Main entry point for writing a combined index to bitcode.
473 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000474
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000475private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000476 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000477 void writeCombinedGlobalValueSummary();
478
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000479 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000480 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000481 if (VMI == GUIDToValueIdMap.end())
482 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000483 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000484 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000485
Teresa Johnson37687f32016-04-23 04:30:47 +0000486 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
487};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000488
Benjamin Kramera65b6102016-05-15 15:18:11 +0000489} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000490
491static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000492 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000493 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000494 case Instruction::Trunc : return bitc::CAST_TRUNC;
495 case Instruction::ZExt : return bitc::CAST_ZEXT;
496 case Instruction::SExt : return bitc::CAST_SEXT;
497 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
498 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
499 case Instruction::UIToFP : return bitc::CAST_UITOFP;
500 case Instruction::SIToFP : return bitc::CAST_SITOFP;
501 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
502 case Instruction::FPExt : return bitc::CAST_FPEXT;
503 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
504 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
505 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000506 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000507 }
508}
509
Teresa Johnson37687f32016-04-23 04:30:47 +0000510static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000511 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000512 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000513 case Instruction::Add:
514 case Instruction::FAdd: return bitc::BINOP_ADD;
515 case Instruction::Sub:
516 case Instruction::FSub: return bitc::BINOP_SUB;
517 case Instruction::Mul:
518 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000519 case Instruction::UDiv: return bitc::BINOP_UDIV;
520 case Instruction::FDiv:
521 case Instruction::SDiv: return bitc::BINOP_SDIV;
522 case Instruction::URem: return bitc::BINOP_UREM;
523 case Instruction::FRem:
524 case Instruction::SRem: return bitc::BINOP_SREM;
525 case Instruction::Shl: return bitc::BINOP_SHL;
526 case Instruction::LShr: return bitc::BINOP_LSHR;
527 case Instruction::AShr: return bitc::BINOP_ASHR;
528 case Instruction::And: return bitc::BINOP_AND;
529 case Instruction::Or: return bitc::BINOP_OR;
530 case Instruction::Xor: return bitc::BINOP_XOR;
531 }
532}
533
Teresa Johnson37687f32016-04-23 04:30:47 +0000534static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000535 switch (Op) {
536 default: llvm_unreachable("Unknown RMW operation!");
537 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
538 case AtomicRMWInst::Add: return bitc::RMW_ADD;
539 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
540 case AtomicRMWInst::And: return bitc::RMW_AND;
541 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
542 case AtomicRMWInst::Or: return bitc::RMW_OR;
543 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
544 case AtomicRMWInst::Max: return bitc::RMW_MAX;
545 case AtomicRMWInst::Min: return bitc::RMW_MIN;
546 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
547 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
548 }
549}
550
Teresa Johnson37687f32016-04-23 04:30:47 +0000551static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000552 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000553 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
554 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
555 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
556 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
557 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
558 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
559 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000560 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000561 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000562}
563
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000564static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
565 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000566 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000567
Chris Lattnere14cb882007-05-04 19:11:41 +0000568 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000569 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
570 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
571 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000572 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000573 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000574
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000575 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000576 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000577}
578
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000579static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
580 switch (Kind) {
581 case Attribute::Alignment:
582 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000583 case Attribute::AllocSize:
584 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000585 case Attribute::AlwaysInline:
586 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000587 case Attribute::ArgMemOnly:
588 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000589 case Attribute::Builtin:
590 return bitc::ATTR_KIND_BUILTIN;
591 case Attribute::ByVal:
592 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000593 case Attribute::Convergent:
594 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000595 case Attribute::InAlloca:
596 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000597 case Attribute::Cold:
598 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000599 case Attribute::InaccessibleMemOnly:
600 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
601 case Attribute::InaccessibleMemOrArgMemOnly:
602 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000603 case Attribute::InlineHint:
604 return bitc::ATTR_KIND_INLINE_HINT;
605 case Attribute::InReg:
606 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000607 case Attribute::JumpTable:
608 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000609 case Attribute::MinSize:
610 return bitc::ATTR_KIND_MIN_SIZE;
611 case Attribute::Naked:
612 return bitc::ATTR_KIND_NAKED;
613 case Attribute::Nest:
614 return bitc::ATTR_KIND_NEST;
615 case Attribute::NoAlias:
616 return bitc::ATTR_KIND_NO_ALIAS;
617 case Attribute::NoBuiltin:
618 return bitc::ATTR_KIND_NO_BUILTIN;
619 case Attribute::NoCapture:
620 return bitc::ATTR_KIND_NO_CAPTURE;
621 case Attribute::NoDuplicate:
622 return bitc::ATTR_KIND_NO_DUPLICATE;
623 case Attribute::NoImplicitFloat:
624 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
625 case Attribute::NoInline:
626 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000627 case Attribute::NoRecurse:
628 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000629 case Attribute::NonLazyBind:
630 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000631 case Attribute::NonNull:
632 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000633 case Attribute::Dereferenceable:
634 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000635 case Attribute::DereferenceableOrNull:
636 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000637 case Attribute::NoRedZone:
638 return bitc::ATTR_KIND_NO_RED_ZONE;
639 case Attribute::NoReturn:
640 return bitc::ATTR_KIND_NO_RETURN;
641 case Attribute::NoUnwind:
642 return bitc::ATTR_KIND_NO_UNWIND;
643 case Attribute::OptimizeForSize:
644 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000645 case Attribute::OptimizeNone:
646 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000647 case Attribute::ReadNone:
648 return bitc::ATTR_KIND_READ_NONE;
649 case Attribute::ReadOnly:
650 return bitc::ATTR_KIND_READ_ONLY;
651 case Attribute::Returned:
652 return bitc::ATTR_KIND_RETURNED;
653 case Attribute::ReturnsTwice:
654 return bitc::ATTR_KIND_RETURNS_TWICE;
655 case Attribute::SExt:
656 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000657 case Attribute::Speculatable:
658 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000659 case Attribute::StackAlignment:
660 return bitc::ATTR_KIND_STACK_ALIGNMENT;
661 case Attribute::StackProtect:
662 return bitc::ATTR_KIND_STACK_PROTECT;
663 case Attribute::StackProtectReq:
664 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
665 case Attribute::StackProtectStrong:
666 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000667 case Attribute::SafeStack:
668 return bitc::ATTR_KIND_SAFESTACK;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +0000669 case Attribute::StrictFP:
670 return bitc::ATTR_KIND_STRICT_FP;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000671 case Attribute::StructRet:
672 return bitc::ATTR_KIND_STRUCT_RET;
673 case Attribute::SanitizeAddress:
674 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +0000675 case Attribute::SanitizeHWAddress:
676 return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000677 case Attribute::SanitizeThread:
678 return bitc::ATTR_KIND_SANITIZE_THREAD;
679 case Attribute::SanitizeMemory:
680 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000681 case Attribute::SwiftError:
682 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000683 case Attribute::SwiftSelf:
684 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000685 case Attribute::UWTable:
686 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000687 case Attribute::WriteOnly:
688 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000689 case Attribute::ZExt:
690 return bitc::ATTR_KIND_Z_EXT;
691 case Attribute::EndAttrKinds:
692 llvm_unreachable("Can not encode end-attribute kinds marker.");
693 case Attribute::None:
694 llvm_unreachable("Can not encode none-attribute.");
695 }
696
697 llvm_unreachable("Trying to encode unknown attribute");
698}
699
Teresa Johnson37687f32016-04-23 04:30:47 +0000700void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000701 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
702 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000703 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000704
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000705 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000706
707 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000708 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
709 unsigned AttrListIndex = Pair.first;
710 AttributeSet AS = Pair.second;
711 Record.push_back(VE.getAttributeGroupID(Pair));
712 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000713
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000714 for (Attribute Attr : AS) {
715 if (Attr.isEnumAttribute()) {
716 Record.push_back(0);
717 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
718 } else if (Attr.isIntAttribute()) {
719 Record.push_back(1);
720 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
721 Record.push_back(Attr.getValueAsInt());
722 } else {
723 StringRef Kind = Attr.getKindAsString();
724 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000725
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000726 Record.push_back(Val.empty() ? 3 : 4);
727 Record.append(Kind.begin(), Kind.end());
728 Record.push_back(0);
729 if (!Val.empty()) {
730 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000731 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000732 }
733 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000734 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000735
736 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
737 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000738 }
739
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000740 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000741}
742
Teresa Johnson37687f32016-04-23 04:30:47 +0000743void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000744 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000745 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000746
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000747 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000748
749 SmallVector<uint64_t, 64> Record;
750 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000751 AttributeList AL = Attrs[i];
752 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
753 AttributeSet AS = AL.getAttributes(i);
754 if (AS.hasAttributes())
755 Record.push_back(VE.getAttributeGroupID({i, AS}));
756 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000757
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000758 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000759 Record.clear();
760 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000761
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000762 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000763}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000764
765/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000766void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000767 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000768
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000769 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000770 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000771
David Blaikie7b028102015-02-25 00:51:52 +0000772 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000773
Chris Lattnerccee7062007-05-05 06:30:12 +0000774 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000775 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000776 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000778 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000779 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Chris Lattnerccee7062007-05-05 06:30:12 +0000781 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000782 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000783 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000785 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000786 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000787 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000788
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000789 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000790 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000791 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000795 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000796
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000797 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000798 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000799 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
801 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000802 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000803
804 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000805 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000806 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000810 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000811
Chris Lattnerccee7062007-05-05 06:30:12 +0000812 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000813 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000814 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000817 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000819 // Emit an entry count so the reader can reserve space.
820 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000821 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000822 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000823
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000824 // Loop over all of the types, emitting each in turn.
825 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000826 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000827 int AbbrevToUse = 0;
828 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000829
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000830 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000831 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
832 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
833 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
834 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
835 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
836 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000837 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000838 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
839 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
840 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000841 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000842 case Type::IntegerTyID:
843 // INTEGER: [width]
844 Code = bitc::TYPE_CODE_INTEGER;
845 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
846 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000847 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000848 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000849 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000850 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000851 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000852 unsigned AddressSpace = PTy->getAddressSpace();
853 TypeVals.push_back(AddressSpace);
854 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000855 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000856 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000857 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000858 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000859 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000860 Code = bitc::TYPE_CODE_FUNCTION;
861 TypeVals.push_back(FT->isVarArg());
862 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000863 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
864 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000865 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000866 break;
867 }
868 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000869 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000870 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000871 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000872 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000873 for (StructType::element_iterator I = ST->element_begin(),
874 E = ST->element_end(); I != E; ++I)
875 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000876
Chris Lattner335d3992011-08-12 18:06:37 +0000877 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000878 Code = bitc::TYPE_CODE_STRUCT_ANON;
879 AbbrevToUse = StructAnonAbbrev;
880 } else {
881 if (ST->isOpaque()) {
882 Code = bitc::TYPE_CODE_OPAQUE;
883 } else {
884 Code = bitc::TYPE_CODE_STRUCT_NAMED;
885 AbbrevToUse = StructNamedAbbrev;
886 }
887
888 // Emit the name if it is present.
889 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000890 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000891 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000892 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000893 break;
894 }
895 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000896 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000897 // ARRAY: [numelts, eltty]
898 Code = bitc::TYPE_CODE_ARRAY;
899 TypeVals.push_back(AT->getNumElements());
900 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000901 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000902 break;
903 }
904 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000905 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000906 // VECTOR [numelts, eltty]
907 Code = bitc::TYPE_CODE_VECTOR;
908 TypeVals.push_back(VT->getNumElements());
909 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
910 break;
911 }
912 }
913
914 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000915 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000916 TypeVals.clear();
917 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000918
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000919 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000920}
921
Teresa Johnson5e22e442016-02-06 16:07:35 +0000922static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
923 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000924 case GlobalValue::ExternalLinkage:
925 return 0;
926 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000927 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000928 case GlobalValue::AppendingLinkage:
929 return 2;
930 case GlobalValue::InternalLinkage:
931 return 3;
932 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000933 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000934 case GlobalValue::ExternalWeakLinkage:
935 return 7;
936 case GlobalValue::CommonLinkage:
937 return 8;
938 case GlobalValue::PrivateLinkage:
939 return 9;
940 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000941 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000942 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000943 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000944 case GlobalValue::AvailableExternallyLinkage:
945 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000946 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000947 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000948}
949
Teresa Johnson5e22e442016-02-06 16:07:35 +0000950static unsigned getEncodedLinkage(const GlobalValue &GV) {
951 return getEncodedLinkage(GV.getLinkage());
952}
953
Charles Saternos75da10d2017-08-04 16:00:58 +0000954static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
955 uint64_t RawFlags = 0;
956 RawFlags |= Flags.ReadNone;
957 RawFlags |= (Flags.ReadOnly << 1);
958 RawFlags |= (Flags.NoRecurse << 2);
959 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
960 return RawFlags;
961}
962
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000963// Decode the flags for GlobalValue in the summary
964static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
965 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000966
Mehdi Amini1380edf2017-02-03 07:41:43 +0000967 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000968 RawFlags |= (Flags.Live << 1);
Sean Fertile4595a912017-11-04 17:04:39 +0000969 RawFlags |= (Flags.DSOLocal << 2);
970
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000971 // Linkage don't need to be remapped at that time for the summary. Any future
972 // change to the getEncodedLinkage() function will need to be taken into
973 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000974 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
975
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000976 return RawFlags;
977}
978
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000979static unsigned getEncodedVisibility(const GlobalValue &GV) {
980 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000981 case GlobalValue::DefaultVisibility: return 0;
982 case GlobalValue::HiddenVisibility: return 1;
983 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000984 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000985 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000986}
987
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000988static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
989 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000990 case GlobalValue::DefaultStorageClass: return 0;
991 case GlobalValue::DLLImportStorageClass: return 1;
992 case GlobalValue::DLLExportStorageClass: return 2;
993 }
994 llvm_unreachable("Invalid DLL storage class");
995}
996
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000997static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000998 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000999 case GlobalVariable::NotThreadLocal: return 0;
1000 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1001 case GlobalVariable::LocalDynamicTLSModel: return 2;
1002 case GlobalVariable::InitialExecTLSModel: return 3;
1003 case GlobalVariable::LocalExecTLSModel: return 4;
1004 }
1005 llvm_unreachable("Invalid TLS model");
1006}
1007
David Majnemerdad0a642014-06-27 18:19:56 +00001008static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1009 switch (C.getSelectionKind()) {
1010 case Comdat::Any:
1011 return bitc::COMDAT_SELECTION_KIND_ANY;
1012 case Comdat::ExactMatch:
1013 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1014 case Comdat::Largest:
1015 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1016 case Comdat::NoDuplicates:
1017 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1018 case Comdat::SameSize:
1019 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1020 }
1021 llvm_unreachable("Invalid selection kind");
1022}
1023
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001024static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1025 switch (GV.getUnnamedAddr()) {
1026 case GlobalValue::UnnamedAddr::None: return 0;
1027 case GlobalValue::UnnamedAddr::Local: return 2;
1028 case GlobalValue::UnnamedAddr::Global: return 1;
1029 }
1030 llvm_unreachable("Invalid unnamed_addr");
1031}
1032
Peter Collingbournec8556152017-07-06 17:56:01 +00001033size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1034 if (GenerateHash)
1035 Hasher.update(Str);
1036 return StrtabBuilder.add(Str);
1037}
1038
Teresa Johnson37687f32016-04-23 04:30:47 +00001039void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +00001040 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +00001041 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001042 // COMDAT: [strtab offset, strtab size, selection_kind]
Peter Collingbournec8556152017-07-06 17:56:01 +00001043 Vals.push_back(addToStrtab(C->getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001044 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +00001045 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001046 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +00001047 Vals.clear();
1048 }
1049}
1050
Teresa Johnsonff642b92015-09-17 20:12:00 +00001051/// Write a record that will eventually hold the word offset of the
1052/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +00001053/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001054void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001055 // Write a placeholder value in for the offset of the real VST,
1056 // which is written after the function blocks so that it can include
1057 // the offset of each function. The placeholder offset will be
1058 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001059 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +00001060 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1061 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1062 // hold the real VST offset. Must use fixed instead of VBR as we don't
1063 // know how many VBR chunks to reserve ahead of time.
1064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001065 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00001066
1067 // Emit the placeholder
1068 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001069 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001070
Teresa Johnson37687f32016-04-23 04:30:47 +00001071 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +00001072 // patched when the real VST is written. We can simply subtract the 32-bit
1073 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001074 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001075}
1076
Teresa Johnsone1164de2016-02-10 21:55:02 +00001077enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1078
1079/// Determine the encoding to use for the given string name and length.
David Blaikieb6b42e02017-06-02 17:24:26 +00001080static StringEncoding getStringEncoding(StringRef Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001081 bool isChar6 = true;
David Blaikieb6b42e02017-06-02 17:24:26 +00001082 for (char C : Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001083 if (isChar6)
David Blaikieb6b42e02017-06-02 17:24:26 +00001084 isChar6 = BitCodeAbbrevOp::isChar6(C);
1085 if ((unsigned char)C & 128)
Teresa Johnsone1164de2016-02-10 21:55:02 +00001086 // don't bother scanning the rest.
1087 return SE_Fixed8;
1088 }
1089 if (isChar6)
1090 return SE_Char6;
David Blaikieb6b42e02017-06-02 17:24:26 +00001091 return SE_Fixed7;
Teresa Johnsone1164de2016-02-10 21:55:02 +00001092}
1093
Teresa Johnsonff642b92015-09-17 20:12:00 +00001094/// Emit top-level description of module, including target triple, inline asm,
1095/// descriptors for global variables, and function prototype info.
1096/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001097void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001098 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001099 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001100 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001101 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001102 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001103 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001104 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001105 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001106 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001107 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001108
Gordon Henriksend930f912008-08-17 18:44:35 +00001109 // Emit information about sections and GC, computing how many there are. Also
1110 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001111 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001112 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001113 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001114 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001115 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001116 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001117 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001118 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001119 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001120 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001121 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001122 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001123 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001124 Entry = SectionMap.size();
1125 }
1126 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001127 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001128 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001129 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1130 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001131 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001132 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001133 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001134 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001135 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001136 Entry = SectionMap.size();
1137 }
1138 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001139 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001140 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001141 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001142 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001143 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1144 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001145 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001146 }
1147 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001148 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001149
Chris Lattner4b00d922007-04-23 16:04:05 +00001150 // Emit abbrev for globals, now that we know # sections and max alignment.
1151 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001152 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001153 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001154 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001155 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001159 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1161 //| explicitType << 1
1162 //| constant
1163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1165 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001166 Abbv->Add(BitCodeAbbrevOp(0));
1167 else {
1168 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001170 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001171 }
1172 if (SectionMap.empty()) // Section.
1173 Abbv->Add(BitCodeAbbrevOp(0));
1174 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001176 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001177 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001178 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001179 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001180
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001181 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001182 // Emit the module's source file name.
1183 {
David Blaikieb6b42e02017-06-02 17:24:26 +00001184 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001185 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1186 if (Bits == SE_Char6)
1187 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1188 else if (Bits == SE_Fixed7)
1189 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1190
1191 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1192 auto Abbv = std::make_shared<BitCodeAbbrev>();
1193 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1194 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1195 Abbv->Add(AbbrevOpToUse);
1196 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1197
1198 for (const auto P : M.getSourceFileName())
1199 Vals.push_back((unsigned char)P);
1200
1201 // Emit the finished record.
1202 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1203 Vals.clear();
1204 }
1205
1206 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001207 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001208 unsigned AbbrevToUse = 0;
1209
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001210 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001211 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001212 // unnamed_addr, externally_initialized, dllstorageclass,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001213 // comdat, attributes, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001214 Vals.push_back(addToStrtab(GV.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001215 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001216 Vals.push_back(VE.getTypeID(GV.getValueType()));
1217 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001218 Vals.push_back(GV.isDeclaration() ? 0 :
1219 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001220 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001221 Vals.push_back(Log2_32(GV.getAlignment())+1);
1222 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1223 if (GV.isThreadLocal() ||
1224 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001225 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1226 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001227 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001228 GV.hasComdat() ||
Sean Fertilec70d28b2017-10-26 15:00:26 +00001229 GV.hasAttributes() ||
1230 GV.isDSOLocal()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001231 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001232 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001233 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001234 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001235 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001236 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001237
1238 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1239 Vals.push_back(VE.getAttributeListID(AL));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001240
1241 Vals.push_back(GV.isDSOLocal());
Chris Lattner4b00d922007-04-23 16:04:05 +00001242 } else {
1243 AbbrevToUse = SimpleGVarAbbrev;
1244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001245
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001246 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001247 Vals.clear();
1248 }
1249
1250 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001251 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001252 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1253 // linkage, paramattrs, alignment, section, visibility, gc,
1254 // unnamed_addr, prologuedata, dllstorageclass, comdat,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001255 // prefixdata, personalityfn, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001256 Vals.push_back(addToStrtab(F.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001257 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001258 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001259 Vals.push_back(F.getCallingConv());
1260 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001261 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001262 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001263 Vals.push_back(Log2_32(F.getAlignment())+1);
1264 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001265 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001266 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001267 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001268 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1269 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001270 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001271 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001272 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1273 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001274 Vals.push_back(
1275 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001276
Sean Fertilec70d28b2017-10-26 15:00:26 +00001277 Vals.push_back(F.isDSOLocal());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001278 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001279 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001280 Vals.clear();
1281 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001282
Chris Lattner44c17072007-04-26 02:46:40 +00001283 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001284 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001285 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001286 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1287 // DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001288 Vals.push_back(addToStrtab(A.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001289 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001290 Vals.push_back(VE.getTypeID(A.getValueType()));
1291 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001292 Vals.push_back(VE.getValueID(A.getAliasee()));
1293 Vals.push_back(getEncodedLinkage(A));
1294 Vals.push_back(getEncodedVisibility(A));
1295 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001296 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001297 Vals.push_back(getEncodedUnnamedAddr(A));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001298 Vals.push_back(A.isDSOLocal());
1299
Chris Lattner44c17072007-04-26 02:46:40 +00001300 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001301 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001302 Vals.clear();
1303 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001304
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001305 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001306 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001307 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001308 // val#, linkage, visibility, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001309 Vals.push_back(addToStrtab(I.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001310 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001311 Vals.push_back(VE.getTypeID(I.getValueType()));
1312 Vals.push_back(I.getType()->getAddressSpace());
1313 Vals.push_back(VE.getValueID(I.getResolver()));
1314 Vals.push_back(getEncodedLinkage(I));
1315 Vals.push_back(getEncodedVisibility(I));
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001316 Vals.push_back(I.isDSOLocal());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001317 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001318 Vals.clear();
1319 }
1320
Teresa Johnson37687f32016-04-23 04:30:47 +00001321 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001322}
1323
Teresa Johnson37687f32016-04-23 04:30:47 +00001324static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001325 uint64_t Flags = 0;
1326
Sanjay Patelc00017d2014-10-15 17:45:13 +00001327 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001328 if (OBO->hasNoSignedWrap())
1329 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1330 if (OBO->hasNoUnsignedWrap())
1331 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001332 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001333 if (PEO->isExact())
1334 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001335 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Sanjay Patel629c4112017-11-06 16:27:15 +00001336 if (FPMO->hasAllowReassoc())
Steven Wu545d34a2018-02-19 19:22:28 +00001337 Flags |= bitc::AllowReassoc;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001338 if (FPMO->hasNoNaNs())
Steven Wu545d34a2018-02-19 19:22:28 +00001339 Flags |= bitc::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001340 if (FPMO->hasNoInfs())
Steven Wu545d34a2018-02-19 19:22:28 +00001341 Flags |= bitc::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001342 if (FPMO->hasNoSignedZeros())
Steven Wu545d34a2018-02-19 19:22:28 +00001343 Flags |= bitc::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001344 if (FPMO->hasAllowReciprocal())
Steven Wu545d34a2018-02-19 19:22:28 +00001345 Flags |= bitc::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001346 if (FPMO->hasAllowContract())
Steven Wu545d34a2018-02-19 19:22:28 +00001347 Flags |= bitc::AllowContract;
Sanjay Patel629c4112017-11-06 16:27:15 +00001348 if (FPMO->hasApproxFunc())
Steven Wu545d34a2018-02-19 19:22:28 +00001349 Flags |= bitc::ApproxFunc;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001350 }
1351
1352 return Flags;
1353}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001354
Teresa Johnson37687f32016-04-23 04:30:47 +00001355void ModuleBitcodeWriter::writeValueAsMetadata(
1356 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001357 // Mimic an MDNode with a value as one operand.
1358 Value *V = MD->getValue();
1359 Record.push_back(VE.getTypeID(V->getType()));
1360 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001361 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001362 Record.clear();
1363}
1364
Teresa Johnson37687f32016-04-23 04:30:47 +00001365void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1366 SmallVectorImpl<uint64_t> &Record,
1367 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001368 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001369 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001370 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1371 "Unexpected function-local metadata");
1372 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001373 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001374 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1375 : bitc::METADATA_NODE,
1376 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001377 Record.clear();
1378}
Devang Patele059ba6e2009-07-23 01:07:34 +00001379
Teresa Johnson37687f32016-04-23 04:30:47 +00001380unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001381 // Assume the column is usually under 128, and always output the inlined-at
1382 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001383 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001384 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001390 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001391}
1392
Teresa Johnson37687f32016-04-23 04:30:47 +00001393void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1394 SmallVectorImpl<uint64_t> &Record,
1395 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001396 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001397 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001398
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001399 Record.push_back(N->isDistinct());
1400 Record.push_back(N->getLine());
1401 Record.push_back(N->getColumn());
1402 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001403 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001404
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001405 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001406 Record.clear();
1407}
1408
Teresa Johnson37687f32016-04-23 04:30:47 +00001409unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001410 // Assume the column is usually under 128, and always output the inlined-at
1411 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001412 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001413 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1414 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1416 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1417 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1418 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1419 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001420 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001421}
1422
Teresa Johnson37687f32016-04-23 04:30:47 +00001423void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1424 SmallVectorImpl<uint64_t> &Record,
1425 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001426 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001427 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001428
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001429 Record.push_back(N->isDistinct());
1430 Record.push_back(N->getTag());
1431 Record.push_back(0); // Per-tag version field; unused for now.
1432
1433 for (auto &I : N->operands())
1434 Record.push_back(VE.getMetadataOrNullID(I));
1435
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001436 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001437 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001438}
1439
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001440static uint64_t rotateSign(int64_t I) {
1441 uint64_t U = I;
1442 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001443}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001444
Teresa Johnson37687f32016-04-23 04:30:47 +00001445void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1446 SmallVectorImpl<uint64_t> &Record,
1447 unsigned Abbrev) {
Sander de Smalenfdf40912018-01-24 09:56:07 +00001448 const uint64_t Version = 1 << 1;
1449 Record.push_back((uint64_t)N->isDistinct() | Version);
1450 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001451 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001452
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001453 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001454 Record.clear();
1455}
1456
Teresa Johnson37687f32016-04-23 04:30:47 +00001457void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1458 SmallVectorImpl<uint64_t> &Record,
1459 unsigned Abbrev) {
Momchil Velikov08dc66e2018-02-12 16:10:09 +00001460 Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001461 Record.push_back(rotateSign(N->getValue()));
1462 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1463
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001464 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001465 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001466}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001467
Teresa Johnson37687f32016-04-23 04:30:47 +00001468void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1469 SmallVectorImpl<uint64_t> &Record,
1470 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001471 Record.push_back(N->isDistinct());
1472 Record.push_back(N->getTag());
1473 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1474 Record.push_back(N->getSizeInBits());
1475 Record.push_back(N->getAlignInBits());
1476 Record.push_back(N->getEncoding());
1477
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001478 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001479 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001480}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001481
Teresa Johnson37687f32016-04-23 04:30:47 +00001482void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1483 SmallVectorImpl<uint64_t> &Record,
1484 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001485 Record.push_back(N->isDistinct());
1486 Record.push_back(N->getTag());
1487 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1488 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1489 Record.push_back(N->getLine());
1490 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001491 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001492 Record.push_back(N->getSizeInBits());
1493 Record.push_back(N->getAlignInBits());
1494 Record.push_back(N->getOffsetInBits());
1495 Record.push_back(N->getFlags());
1496 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1497
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001498 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1499 // that there is no DWARF address space associated with DIDerivedType.
1500 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1501 Record.push_back(*DWARFAddressSpace + 1);
1502 else
1503 Record.push_back(0);
1504
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001505 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001506 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001507}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001508
Teresa Johnson37687f32016-04-23 04:30:47 +00001509void ModuleBitcodeWriter::writeDICompositeType(
1510 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1511 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001512 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001513 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001514 Record.push_back(N->getTag());
1515 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1516 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1517 Record.push_back(N->getLine());
1518 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1519 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1520 Record.push_back(N->getSizeInBits());
1521 Record.push_back(N->getAlignInBits());
1522 Record.push_back(N->getOffsetInBits());
1523 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001524 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001525 Record.push_back(N->getRuntimeLang());
1526 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001527 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001528 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
Adrian Prantl8c599212018-02-06 23:45:59 +00001529 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001530
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001531 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001532 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001533}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001534
Teresa Johnson37687f32016-04-23 04:30:47 +00001535void ModuleBitcodeWriter::writeDISubroutineType(
1536 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1537 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001538 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001539 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001540 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001541 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001542 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001543
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001544 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001545 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001546}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001547
Teresa Johnson37687f32016-04-23 04:30:47 +00001548void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1549 SmallVectorImpl<uint64_t> &Record,
1550 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001551 Record.push_back(N->isDistinct());
1552 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1553 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Scott Linder71603842018-02-12 19:45:54 +00001554 if (N->getRawChecksum()) {
1555 Record.push_back(N->getRawChecksum()->Kind);
1556 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1557 } else {
1558 // Maintain backwards compatibility with the old internal representation of
1559 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1560 Record.push_back(0);
1561 Record.push_back(VE.getMetadataOrNullID(nullptr));
1562 }
Scott Linder16c7bda2018-02-23 23:01:06 +00001563 auto Source = N->getRawSource();
1564 if (Source)
1565 Record.push_back(VE.getMetadataOrNullID(*Source));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001566
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001567 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001568 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001569}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001570
Teresa Johnson37687f32016-04-23 04:30:47 +00001571void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1572 SmallVectorImpl<uint64_t> &Record,
1573 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001574 assert(N->isDistinct() && "Expected distinct compile units");
1575 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001576 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001577 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001578 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1579 Record.push_back(N->isOptimized());
1580 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1581 Record.push_back(N->getRuntimeVersion());
1582 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1583 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001584 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1585 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001586 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001587 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1588 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001589 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001590 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001591 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001592 Record.push_back(N->getDebugInfoForProfiling());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001593 Record.push_back(N->getGnuPubnames());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001594
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001595 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001596 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001597}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001598
Teresa Johnson37687f32016-04-23 04:30:47 +00001599void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1600 SmallVectorImpl<uint64_t> &Record,
1601 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001602 uint64_t HasUnitFlag = 1 << 1;
1603 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001604 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1605 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1606 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1607 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1608 Record.push_back(N->getLine());
1609 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1610 Record.push_back(N->isLocalToUnit());
1611 Record.push_back(N->isDefinition());
1612 Record.push_back(N->getScopeLine());
1613 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1614 Record.push_back(N->getVirtuality());
1615 Record.push_back(N->getVirtualIndex());
1616 Record.push_back(N->getFlags());
1617 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001618 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001619 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001620 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001621 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001622 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001623 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001624
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001625 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001626 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001627}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001628
Teresa Johnson37687f32016-04-23 04:30:47 +00001629void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1630 SmallVectorImpl<uint64_t> &Record,
1631 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001632 Record.push_back(N->isDistinct());
1633 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1634 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1635 Record.push_back(N->getLine());
1636 Record.push_back(N->getColumn());
1637
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001638 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001639 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001640}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001641
Teresa Johnson37687f32016-04-23 04:30:47 +00001642void ModuleBitcodeWriter::writeDILexicalBlockFile(
1643 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1644 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001645 Record.push_back(N->isDistinct());
1646 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1647 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1648 Record.push_back(N->getDiscriminator());
1649
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001650 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001651 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001652}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001653
Teresa Johnson37687f32016-04-23 04:30:47 +00001654void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1655 SmallVectorImpl<uint64_t> &Record,
1656 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001657 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001658 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001659 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001660
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001661 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001662 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001663}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001664
Teresa Johnson37687f32016-04-23 04:30:47 +00001665void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1666 SmallVectorImpl<uint64_t> &Record,
1667 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001668 Record.push_back(N->isDistinct());
1669 Record.push_back(N->getMacinfoType());
1670 Record.push_back(N->getLine());
1671 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1672 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1673
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001674 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001675 Record.clear();
1676}
1677
Teresa Johnson37687f32016-04-23 04:30:47 +00001678void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1679 SmallVectorImpl<uint64_t> &Record,
1680 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001681 Record.push_back(N->isDistinct());
1682 Record.push_back(N->getMacinfoType());
1683 Record.push_back(N->getLine());
1684 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1685 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1686
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001687 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001688 Record.clear();
1689}
1690
Teresa Johnson37687f32016-04-23 04:30:47 +00001691void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1692 SmallVectorImpl<uint64_t> &Record,
1693 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001694 Record.push_back(N->isDistinct());
1695 for (auto &I : N->operands())
1696 Record.push_back(VE.getMetadataOrNullID(I));
1697
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001698 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001699 Record.clear();
1700}
1701
Teresa Johnson37687f32016-04-23 04:30:47 +00001702void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1703 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1704 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001705 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001706 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1707 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1708
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001709 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001710 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001711}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001712
Teresa Johnson37687f32016-04-23 04:30:47 +00001713void ModuleBitcodeWriter::writeDITemplateValueParameter(
1714 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1715 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001716 Record.push_back(N->isDistinct());
1717 Record.push_back(N->getTag());
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 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1721
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001722 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001723 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001724}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001725
Teresa Johnson37687f32016-04-23 04:30:47 +00001726void ModuleBitcodeWriter::writeDIGlobalVariable(
1727 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1728 unsigned Abbrev) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001729 const uint64_t Version = 1 << 1;
1730 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001731 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1732 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1733 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1734 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1735 Record.push_back(N->getLine());
1736 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1737 Record.push_back(N->isLocalToUnit());
1738 Record.push_back(N->isDefinition());
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001739 Record.push_back(/* expr */ 0);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001740 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001741 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001742
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001743 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001744 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001745}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001746
Teresa Johnson37687f32016-04-23 04:30:47 +00001747void ModuleBitcodeWriter::writeDILocalVariable(
1748 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1749 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001750 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001751 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001752 // 1) Record has no artificial tag (Record[1]),
1753 // has no obsolete inlinedAt field (Record[9]).
1754 // In this case Record size will be 8, HasAlignment flag is false.
1755 // 2) Record has artificial tag (Record[1]),
1756 // has no obsolete inlignedAt field (Record[9]).
1757 // In this case Record size will be 9, HasAlignment flag is false.
1758 // 3) Record has both artificial tag (Record[1]) and
1759 // obsolete inlignedAt field (Record[9]).
1760 // In this case Record size will be 10, HasAlignment flag is false.
1761 // 4) Record has neither artificial tag, nor inlignedAt field, but
1762 // HasAlignment flag is true and Record[8] contains alignment value.
1763 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001764 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001765 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1766 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1767 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1768 Record.push_back(N->getLine());
1769 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1770 Record.push_back(N->getArg());
1771 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001772 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001773
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001774 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001775 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001776}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001777
Teresa Johnson37687f32016-04-23 04:30:47 +00001778void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1779 SmallVectorImpl<uint64_t> &Record,
1780 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001781 Record.reserve(N->getElements().size() + 1);
Florian Hahnffc498d2017-06-14 13:14:38 +00001782 const uint64_t Version = 3 << 1;
Adrian Prantl6825fb62017-04-18 01:21:53 +00001783 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001784 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001785
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001786 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001787 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001788}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001789
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001790void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1791 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1792 unsigned Abbrev) {
1793 Record.push_back(N->isDistinct());
1794 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1795 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
Charles Saternos75da10d2017-08-04 16:00:58 +00001796
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001797 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1798 Record.clear();
1799}
1800
Teresa Johnson37687f32016-04-23 04:30:47 +00001801void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1802 SmallVectorImpl<uint64_t> &Record,
1803 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001804 Record.push_back(N->isDistinct());
1805 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1806 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1807 Record.push_back(N->getLine());
1808 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1809 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1810 Record.push_back(N->getAttributes());
1811 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1812
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001813 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001814 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001815}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001816
Teresa Johnson37687f32016-04-23 04:30:47 +00001817void ModuleBitcodeWriter::writeDIImportedEntity(
1818 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1819 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001820 Record.push_back(N->isDistinct());
1821 Record.push_back(N->getTag());
1822 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1823 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1824 Record.push_back(N->getLine());
1825 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Adrian Prantld63bfd22017-07-19 00:09:54 +00001826 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001827
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001828 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001829 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001830}
1831
Teresa Johnson37687f32016-04-23 04:30:47 +00001832unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001833 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001834 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1835 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1836 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001837 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001838}
1839
Teresa Johnson37687f32016-04-23 04:30:47 +00001840void ModuleBitcodeWriter::writeNamedMetadata(
1841 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001842 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001843 return;
1844
Teresa Johnson37687f32016-04-23 04:30:47 +00001845 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001846 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001847 // Write name.
1848 StringRef Str = NMD.getName();
1849 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001850 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001851 Record.clear();
1852
1853 // Write named metadata operands.
1854 for (const MDNode *N : NMD.operands())
1855 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001856 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001857 Record.clear();
1858 }
1859}
1860
Teresa Johnson37687f32016-04-23 04:30:47 +00001861unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001862 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001863 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1866 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001867 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001868}
1869
1870/// Write out a record for MDString.
1871///
1872/// All the metadata strings in a metadata block are emitted in a single
1873/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001874void ModuleBitcodeWriter::writeMetadataStrings(
1875 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001876 if (Strings.empty())
1877 return;
1878
1879 // Start the record with the number of strings.
1880 Record.push_back(bitc::METADATA_STRINGS);
1881 Record.push_back(Strings.size());
1882
1883 // Emit the sizes of the strings in the blob.
1884 SmallString<256> Blob;
1885 {
1886 BitstreamWriter W(Blob);
1887 for (const Metadata *MD : Strings)
1888 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1889 W.FlushToWord();
1890 }
1891
1892 // Add the offset to the strings to the record.
1893 Record.push_back(Blob.size());
1894
1895 // Add the strings to the blob.
1896 for (const Metadata *MD : Strings)
1897 Blob.append(cast<MDString>(MD)->getString());
1898
1899 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001900 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001901 Record.clear();
1902}
1903
Mehdi Aminie98f9252016-12-28 22:30:28 +00001904// Generates an enum to use as an index in the Abbrev array of Metadata record.
1905enum MetadataAbbrev : unsigned {
1906#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1907#include "llvm/IR/Metadata.def"
1908 LastPlusOne
1909};
1910
Teresa Johnson37687f32016-04-23 04:30:47 +00001911void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001912 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1913 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001914 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001915 return;
1916
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001917 // Initialize MDNode abbreviations.
1918#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1919#include "llvm/IR/Metadata.def"
1920
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001921 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001922 if (IndexPos)
1923 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001924 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001925 assert(N->isResolved() && "Expected forward references to be resolved");
1926
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001927 switch (N->getMetadataID()) {
1928 default:
1929 llvm_unreachable("Invalid MDNode subclass");
1930#define HANDLE_MDNODE_LEAF(CLASS) \
1931 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001932 if (MDAbbrevs) \
1933 write##CLASS(cast<CLASS>(N), Record, \
1934 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1935 else \
1936 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001937 continue;
1938#include "llvm/IR/Metadata.def"
1939 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001940 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001941 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001942 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001943}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001944
Teresa Johnson37687f32016-04-23 04:30:47 +00001945void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001946 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001947 return;
1948
Mehdi Aminie98f9252016-12-28 22:30:28 +00001949 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001950 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001951
1952 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1953 // block and load any metadata.
1954 std::vector<unsigned> MDAbbrevs;
1955
1956 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1957 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1958 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1959 createGenericDINodeAbbrev();
1960
David Blaikie7ad9dc12017-01-04 22:36:33 +00001961 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001962 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001965 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001966
David Blaikie7ad9dc12017-01-04 22:36:33 +00001967 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001968 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001971 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001972
1973 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00001974 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00001975
1976 // We only emit an index for the metadata record if we have more than a given
1977 // (naive) threshold of metadatas, otherwise it is not worth it.
1978 if (VE.getNonMDStrings().size() > IndexThreshold) {
1979 // Write a placeholder value in for the offset of the metadata index,
1980 // which is written after the records, so that it can include
1981 // the offset of each entry. The placeholder offset will be
1982 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00001983 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00001984 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1985 }
1986
1987 // Compute and save the bit offset to the current position, which will be
1988 // patched when we emit the index later. We can simply subtract the 64-bit
1989 // fixed size from the current bit number to get the location to backpatch.
1990 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1991
1992 // This index will contain the bitpos for each individual record.
1993 std::vector<uint64_t> IndexPos;
1994 IndexPos.reserve(VE.getNonMDStrings().size());
1995
1996 // Write all the records
1997 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1998
1999 if (VE.getNonMDStrings().size() > IndexThreshold) {
2000 // Now that we have emitted all the records we will emit the index. But
2001 // first
2002 // backpatch the forward reference so that the reader can skip the records
2003 // efficiently.
2004 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2005 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2006
2007 // Delta encode the index.
2008 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2009 for (auto &Elt : IndexPos) {
2010 auto EltDelta = Elt - PreviousValue;
2011 PreviousValue = Elt;
2012 Elt = EltDelta;
2013 }
2014 // Emit the index record.
2015 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2016 IndexPos.clear();
2017 }
2018
2019 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002020 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00002021
2022 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2023 SmallVector<uint64_t, 4> Record;
2024 Record.push_back(VE.getValueID(&GO));
2025 pushGlobalMetadataAttachment(Record, GO);
2026 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2027 };
2028 for (const Function &F : M)
2029 if (F.isDeclaration() && F.hasMetadata())
2030 AddDeclAttachedMetadata(F);
2031 // FIXME: Only store metadata for declarations here, and move data for global
2032 // variable definitions to a separate block (PR28134).
2033 for (const GlobalVariable &GV : M.globals())
2034 if (GV.hasMetadata())
2035 AddDeclAttachedMetadata(GV);
2036
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002037 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002038}
2039
Teresa Johnson37687f32016-04-23 04:30:47 +00002040void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00002041 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002042 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002043
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002044 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002045 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00002046 writeMetadataStrings(VE.getMDStrings(), Record);
2047 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002048 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00002049}
2050
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002051void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2052 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2053 // [n x [id, mdnode]]
2054 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2055 GO.getAllMetadata(MDs);
2056 for (const auto &I : MDs) {
2057 Record.push_back(I.first);
2058 Record.push_back(VE.getMetadataID(I.second));
2059 }
2060}
2061
2062void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002063 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00002064
Devang Patelaf206b82009-09-18 19:26:43 +00002065 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002066
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002067 if (F.hasMetadata()) {
2068 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002069 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002070 Record.clear();
2071 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002072
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002073 // Write metadata attachments
2074 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2075 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002076 for (const BasicBlock &BB : F)
2077 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00002078 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002079 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002080
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002081 // If no metadata, ignore instruction.
2082 if (MDs.empty()) continue;
2083
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002084 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002085
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002086 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2087 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002088 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00002089 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002090 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002091 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00002092 }
2093
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002094 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002095}
2096
Peter Collingbourne21521892016-06-21 23:42:48 +00002097void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00002098 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002099
Devang Patelaf206b82009-09-18 19:26:43 +00002100 // Write metadata kinds
2101 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00002102 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002103 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002104
Dan Gohman43aa8f02010-07-20 21:42:28 +00002105 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00002106
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002107 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002108
Dan Gohman43aa8f02010-07-20 21:42:28 +00002109 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00002110 Record.push_back(MDKindID);
2111 StringRef KName = Names[MDKindID];
2112 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002113
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002114 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00002115 Record.clear();
2116 }
2117
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002118 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002119}
2120
Teresa Johnson37687f32016-04-23 04:30:47 +00002121void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002122 // Write metadata kinds
2123 //
2124 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2125 //
2126 // OPERAND_BUNDLE_TAG - [strchr x N]
2127
2128 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002129 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002130
2131 if (Tags.empty())
2132 return;
2133
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002134 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002135
2136 SmallVector<uint64_t, 64> Record;
2137
2138 for (auto Tag : Tags) {
2139 Record.append(Tag.begin(), Tag.end());
2140
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002141 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002142 Record.clear();
2143 }
2144
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002145 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002146}
2147
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002148void ModuleBitcodeWriter::writeSyncScopeNames() {
2149 SmallVector<StringRef, 8> SSNs;
2150 M.getContext().getSyncScopeNames(SSNs);
2151 if (SSNs.empty())
2152 return;
2153
2154 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2155
2156 SmallVector<uint64_t, 64> Record;
2157 for (auto SSN : SSNs) {
2158 Record.append(SSN.begin(), SSN.end());
2159 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2160 Record.clear();
2161 }
2162
2163 Stream.ExitBlock();
2164}
2165
Jan Wen Voungafaced02012-10-11 20:20:40 +00002166static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2167 if ((int64_t)V >= 0)
2168 Vals.push_back(V << 1);
2169 else
2170 Vals.push_back((-V << 1) | 1);
2171}
2172
Teresa Johnson37687f32016-04-23 04:30:47 +00002173void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2174 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002175 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002176
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002177 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002178
2179 unsigned AggregateAbbrev = 0;
2180 unsigned String8Abbrev = 0;
2181 unsigned CString7Abbrev = 0;
2182 unsigned CString6Abbrev = 0;
2183 // If this is a constant pool for the module, emit module-specific abbrevs.
2184 if (isGlobal) {
2185 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002186 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002187 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002190 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002191
2192 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002193 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002194 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2195 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2196 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002197 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002198 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002199 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002200 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002203 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002204 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002205 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002206 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2207 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002209 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210 }
2211
Devang Patel8cca7b42009-08-04 05:01:35 +00002212 SmallVector<uint64_t, 64> Record;
2213
2214 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002215 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002216 for (unsigned i = FirstVal; i != LastVal; ++i) {
2217 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002218 // If we need to switch types, do so now.
2219 if (V->getType() != LastTy) {
2220 LastTy = V->getType();
2221 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002222 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2223 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002224 Record.clear();
2225 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002226
Chris Lattner52523562007-04-24 00:16:04 +00002227 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002228 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002229 unsigned(IA->isAlignStack()) << 1 |
2230 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002231
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002232 // Add the asm string.
2233 const std::string &AsmStr = IA->getAsmString();
2234 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002235 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002236
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002237 // Add the constraint string.
2238 const std::string &ConstraintStr = IA->getConstraintString();
2239 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002240 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002241 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002242 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002243 continue;
2244 }
2245 const Constant *C = cast<Constant>(V);
2246 unsigned Code = -1U;
2247 unsigned AbbrevToUse = 0;
2248 if (C->isNullValue()) {
2249 Code = bitc::CST_CODE_NULL;
2250 } else if (isa<UndefValue>(C)) {
2251 Code = bitc::CST_CODE_UNDEF;
2252 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002253 if (IV->getBitWidth() <= 64) {
2254 uint64_t V = IV->getSExtValue();
2255 emitSignedInt64(Record, V);
2256 Code = bitc::CST_CODE_INTEGER;
2257 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2258 } else { // Wide integers, > 64 bits in size.
2259 // We have an arbitrary precision integer value to write whose
2260 // bit width is > 64. However, in canonical unsigned integer
2261 // format it is likely that the high bits are going to be zero.
2262 // So, we only write the number of active words.
2263 unsigned NWords = IV->getValue().getActiveWords();
2264 const uint64_t *RawWords = IV->getValue().getRawData();
2265 for (unsigned i = 0; i != NWords; ++i) {
2266 emitSignedInt64(Record, RawWords[i]);
2267 }
2268 Code = bitc::CST_CODE_WIDE_INTEGER;
2269 }
Chris Lattner52523562007-04-24 00:16:04 +00002270 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2271 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002272 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002273 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002274 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002275 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002276 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002277 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002278 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002279 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002280 Record.push_back((p[1] << 48) | (p[0] >> 16));
2281 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002282 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002283 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002284 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002285 Record.push_back(p[0]);
2286 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002287 } else {
Eugene Zelenko975293f2017-09-07 23:28:24 +00002288 assert(0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002289 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002290 } else if (isa<ConstantDataSequential>(C) &&
2291 cast<ConstantDataSequential>(C)->isString()) {
2292 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2293 // Emit constant strings specially.
2294 unsigned NumElts = Str->getNumElements();
2295 // If this is a null-terminated string, use the denser CSTRING encoding.
2296 if (Str->isCString()) {
2297 Code = bitc::CST_CODE_CSTRING;
2298 --NumElts; // Don't encode the null, which isn't allowed by char6.
2299 } else {
2300 Code = bitc::CST_CODE_STRING;
2301 AbbrevToUse = String8Abbrev;
2302 }
2303 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2304 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2305 for (unsigned i = 0; i != NumElts; ++i) {
2306 unsigned char V = Str->getElementAsInteger(i);
2307 Record.push_back(V);
2308 isCStr7 &= (V & 128) == 0;
2309 if (isCStrChar6)
2310 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2311 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002312
Chris Lattner372dd1e2012-01-30 00:51:16 +00002313 if (isCStrChar6)
2314 AbbrevToUse = CString6Abbrev;
2315 else if (isCStr7)
2316 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002317 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002318 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002319 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002320 Type *EltTy = CDS->getType()->getElementType();
2321 if (isa<IntegerType>(EltTy)) {
2322 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2323 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002324 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002325 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2326 Record.push_back(
2327 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002328 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002329 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002330 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002331 for (const Value *Op : C->operands())
2332 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002333 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002334 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002335 switch (CE->getOpcode()) {
2336 default:
2337 if (Instruction::isCast(CE->getOpcode())) {
2338 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002339 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002340 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2341 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002342 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002343 } else {
2344 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2345 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002346 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002347 Record.push_back(VE.getValueID(C->getOperand(0)));
2348 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002349 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002350 if (Flags != 0)
2351 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002352 }
2353 break;
David Blaikieb9263572015-03-13 21:03:36 +00002354 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002355 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002356 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002357 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002358 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2359 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2360 Record.push_back((*Idx << 1) | GO->isInBounds());
2361 } else if (GO->isInBounds())
2362 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002363 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2364 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2365 Record.push_back(VE.getValueID(C->getOperand(i)));
2366 }
2367 break;
David Blaikieb9263572015-03-13 21:03:36 +00002368 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002369 case Instruction::Select:
2370 Code = bitc::CST_CODE_CE_SELECT;
2371 Record.push_back(VE.getValueID(C->getOperand(0)));
2372 Record.push_back(VE.getValueID(C->getOperand(1)));
2373 Record.push_back(VE.getValueID(C->getOperand(2)));
2374 break;
2375 case Instruction::ExtractElement:
2376 Code = bitc::CST_CODE_CE_EXTRACTELT;
2377 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2378 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002379 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002380 Record.push_back(VE.getValueID(C->getOperand(1)));
2381 break;
2382 case Instruction::InsertElement:
2383 Code = bitc::CST_CODE_CE_INSERTELT;
2384 Record.push_back(VE.getValueID(C->getOperand(0)));
2385 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002386 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002387 Record.push_back(VE.getValueID(C->getOperand(2)));
2388 break;
2389 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002390 // If the return type and argument types are the same, this is a
2391 // standard shufflevector instruction. If the types are different,
2392 // then the shuffle is widening or truncating the input vectors, and
2393 // the argument type must also be encoded.
2394 if (C->getType() == C->getOperand(0)->getType()) {
2395 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2396 } else {
2397 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2398 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2399 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002400 Record.push_back(VE.getValueID(C->getOperand(0)));
2401 Record.push_back(VE.getValueID(C->getOperand(1)));
2402 Record.push_back(VE.getValueID(C->getOperand(2)));
2403 break;
2404 case Instruction::ICmp:
2405 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002406 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002407 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2408 Record.push_back(VE.getValueID(C->getOperand(0)));
2409 Record.push_back(VE.getValueID(C->getOperand(1)));
2410 Record.push_back(CE->getPredicate());
2411 break;
2412 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002413 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002414 Code = bitc::CST_CODE_BLOCKADDRESS;
2415 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2416 Record.push_back(VE.getValueID(BA->getFunction()));
2417 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002418 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002419#ifndef NDEBUG
2420 C->dump();
2421#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002422 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002423 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002424 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002425 Record.clear();
2426 }
2427
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002428 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002429}
2430
Teresa Johnson37687f32016-04-23 04:30:47 +00002431void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002432 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002433
Chris Lattner52523562007-04-24 00:16:04 +00002434 // Find the first constant to emit, which is the first non-globalvalue value.
2435 // We know globalvalues have been emitted by WriteModuleInfo.
2436 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2437 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002438 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002439 return;
2440 }
2441 }
2442}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002443
Teresa Johnson37687f32016-04-23 04:30:47 +00002444/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002445/// many values, because we need to know what type to create for forward
2446/// references. However, most operands are not forward references, so this type
2447/// field is not needed.
2448///
2449/// This function adds V's value ID to Vals. If the value ID is higher than the
2450/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002451/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002452bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2453 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002454 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002455 // Make encoding relative to the InstID.
2456 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002457 if (ValID >= InstID) {
2458 Vals.push_back(VE.getTypeID(V->getType()));
2459 return true;
2460 }
2461 return false;
2462}
2463
Teresa Johnson37687f32016-04-23 04:30:47 +00002464void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2465 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002466 SmallVector<unsigned, 64> Record;
2467 LLVMContext &C = CS.getInstruction()->getContext();
2468
2469 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002470 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002471 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002472
2473 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002474 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002475
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002476 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002477 Record.clear();
2478 }
2479}
2480
Teresa Johnson37687f32016-04-23 04:30:47 +00002481/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002482/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002483void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2484 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002485 unsigned ValID = VE.getValueID(V);
2486 Vals.push_back(InstID - ValID);
2487}
2488
Teresa Johnson37687f32016-04-23 04:30:47 +00002489void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2490 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002491 unsigned ValID = VE.getValueID(V);
2492 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2493 emitSignedInt64(Vals, diff);
2494}
2495
Chris Lattnere6e364c2007-04-26 05:53:54 +00002496/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002497void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2498 unsigned InstID,
2499 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002500 unsigned Code = 0;
2501 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002502 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002503 switch (I.getOpcode()) {
2504 default:
2505 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002506 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002507 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002508 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002509 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002510 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002511 } else {
2512 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002513 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002514 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002515 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002516 pushValue(I.getOperand(1), InstID, Vals);
2517 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2518 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002519 if (Flags != 0) {
2520 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2521 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2522 Vals.push_back(Flags);
2523 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002524 }
2525 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002526
David Blaikieb5b5efd2015-02-25 01:08:52 +00002527 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002528 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002529 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2530 auto &GEPInst = cast<GetElementPtrInst>(I);
2531 Vals.push_back(GEPInst.isInBounds());
2532 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002533 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002534 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002535 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002536 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002537 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002538 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002539 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002540 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002541 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002542 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002543 }
2544 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002545 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002546 pushValueAndType(I.getOperand(0), InstID, Vals);
2547 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002548 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002549 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002550 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002551 }
Chris Lattner0a603252007-05-01 02:13:26 +00002552 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002553 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002554 pushValueAndType(I.getOperand(1), InstID, Vals);
2555 pushValue(I.getOperand(2), InstID, Vals);
2556 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002557 break;
2558 case Instruction::ExtractElement:
2559 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002560 pushValueAndType(I.getOperand(0), InstID, Vals);
2561 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002562 break;
2563 case Instruction::InsertElement:
2564 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002565 pushValueAndType(I.getOperand(0), InstID, Vals);
2566 pushValue(I.getOperand(1), InstID, Vals);
2567 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002568 break;
2569 case Instruction::ShuffleVector:
2570 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002571 pushValueAndType(I.getOperand(0), InstID, Vals);
2572 pushValue(I.getOperand(1), InstID, Vals);
2573 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002574 break;
2575 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002576 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002577 // compare returning Int1Ty or vector of Int1Ty
2578 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002579 pushValueAndType(I.getOperand(0), InstID, Vals);
2580 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002581 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002582 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002583 if (Flags != 0)
2584 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002585 break;
James Molloy88eb5352015-07-10 12:52:00 +00002586 }
Chris Lattner0a603252007-05-01 02:13:26 +00002587
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002588 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002589 {
2590 Code = bitc::FUNC_CODE_INST_RET;
2591 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002592 if (NumOperands == 0)
2593 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2594 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002595 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002596 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2597 } else {
2598 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002599 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002600 }
2601 }
Chris Lattner0a603252007-05-01 02:13:26 +00002602 break;
2603 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002604 {
2605 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002606 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002607 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2608 if (II.isConditional()) {
2609 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002610 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002611 }
Chris Lattner0a603252007-05-01 02:13:26 +00002612 }
2613 break;
2614 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002615 {
2616 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002617 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002618 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002619 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002620 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002621 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002622 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2623 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002624 }
2625 }
Chris Lattner0a603252007-05-01 02:13:26 +00002626 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002627 case Instruction::IndirectBr:
2628 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002629 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002630 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002631 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002632 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002633 Vals.push_back(VE.getValueID(I.getOperand(i)));
2634 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002635
Chris Lattnerb811e952007-05-01 07:03:37 +00002636 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002637 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002638 const Value *Callee = II->getCalledValue();
2639 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002640
2641 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002642 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002643
Chris Lattner0a603252007-05-01 02:13:26 +00002644 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002645
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002646 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002647 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002648 Vals.push_back(VE.getValueID(II->getNormalDest()));
2649 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002650 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002651 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652
Chris Lattner0a603252007-05-01 02:13:26 +00002653 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002654 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002655 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002656
2657 // Emit type/value pairs for varargs params.
2658 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002659 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002660 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002661 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002662 }
2663 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002664 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002665 case Instruction::Resume:
2666 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002667 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002668 break;
David Majnemer654e1302015-07-31 17:58:14 +00002669 case Instruction::CleanupRet: {
2670 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2671 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002672 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002673 if (CRI.hasUnwindDest())
2674 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2675 break;
2676 }
2677 case Instruction::CatchRet: {
2678 Code = bitc::FUNC_CODE_INST_CATCHRET;
2679 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002680 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002681 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2682 break;
2683 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002684 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002685 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002686 const auto &FuncletPad = cast<FuncletPadInst>(I);
2687 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2688 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002689 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002690
2691 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002692 Vals.push_back(NumArgOperands);
2693 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002694 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002695 break;
2696 }
2697 case Instruction::CatchSwitch: {
2698 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2699 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2700
Teresa Johnson37687f32016-04-23 04:30:47 +00002701 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002702
2703 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2704 Vals.push_back(NumHandlers);
2705 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2706 Vals.push_back(VE.getValueID(CatchPadBB));
2707
2708 if (CatchSwitch.hasUnwindDest())
2709 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002710 break;
2711 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002712 case Instruction::Unreachable:
2713 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002714 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002715 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002716
Jay Foad372ad642011-06-20 14:18:48 +00002717 case Instruction::PHI: {
2718 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002719 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002720 // With the newer instruction encoding, forward references could give
2721 // negative valued IDs. This is most common for PHIs, so we use
2722 // signed VBRs.
2723 SmallVector<uint64_t, 128> Vals64;
2724 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002725 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002726 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002727 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002728 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002729 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002730 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002731 Vals64.clear();
2732 return;
Jay Foad372ad642011-06-20 14:18:48 +00002733 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002734
Bill Wendlingfae14752011-08-12 20:24:12 +00002735 case Instruction::LandingPad: {
2736 const LandingPadInst &LP = cast<LandingPadInst>(I);
2737 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2738 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002739 Vals.push_back(LP.isCleanup());
2740 Vals.push_back(LP.getNumClauses());
2741 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2742 if (LP.isCatch(I))
2743 Vals.push_back(LandingPadInst::Catch);
2744 else
2745 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002746 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002747 }
2748 break;
2749 }
2750
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002751 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002752 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002753 const AllocaInst &AI = cast<AllocaInst>(I);
2754 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002755 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002756 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002757 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2758 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2759 "not enough bits for maximum alignment");
2760 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2761 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002762 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002763 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002764 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002765 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002766 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002767
Chris Lattner0a603252007-05-01 02:13:26 +00002768 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002769 if (cast<LoadInst>(I).isAtomic()) {
2770 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002771 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002772 } else {
2773 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002774 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002775 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2776 }
David Blaikie85035652015-02-25 01:07:20 +00002777 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002778 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2779 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002780 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002781 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002782 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002783 }
Chris Lattner0a603252007-05-01 02:13:26 +00002784 break;
2785 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002786 if (cast<StoreInst>(I).isAtomic())
2787 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2788 else
2789 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002790 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2791 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002792 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2793 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002794 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002795 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002796 Vals.push_back(
2797 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002798 }
Chris Lattner0a603252007-05-01 02:13:26 +00002799 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002800 case Instruction::AtomicCmpXchg:
2801 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002802 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2803 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2804 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002805 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002806 Vals.push_back(
2807 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2808 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002809 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002810 Vals.push_back(
2811 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002812 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002813 break;
2814 case Instruction::AtomicRMW:
2815 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002816 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2817 pushValue(I.getOperand(1), InstID, Vals); // val.
2818 Vals.push_back(
2819 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002820 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002821 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2822 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002823 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002824 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002825 case Instruction::Fence:
2826 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002827 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002828 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002829 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002830 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002831 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002832 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002833
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002834 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002835 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002836
Chris Lattnerc44070802011-06-17 18:17:37 +00002837 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002838
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002839 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002840
Teresa Johnson37687f32016-04-23 04:30:47 +00002841 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002842 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2843 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2844 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2845 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002846 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2847 unsigned(Flags != 0) << bitc::CALL_FMF);
2848 if (Flags != 0)
2849 Vals.push_back(Flags);
2850
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002851 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002852 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002853
Chris Lattner0a603252007-05-01 02:13:26 +00002854 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002855 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2856 // Check for labels (can happen with asm labels).
2857 if (FTy->getParamType(i)->isLabelTy())
2858 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2859 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002860 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002861 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002862
Chris Lattnerb811e952007-05-01 07:03:37 +00002863 // Emit type/value pairs for varargs params.
2864 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002865 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002866 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002867 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002868 }
2869 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002870 }
Chris Lattner0a603252007-05-01 02:13:26 +00002871 case Instruction::VAArg:
2872 Code = bitc::FUNC_CODE_INST_VAARG;
2873 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002874 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002875 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2876 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002877 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002879 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002880 Vals.clear();
2881}
2882
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002883/// Write a GlobalValue VST to the module. The purpose of this data structure is
2884/// to allow clients to efficiently find the function body.
2885void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2886 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2887 // Get the offset of the VST we are writing, and backpatch it into
2888 // the VST forward declaration record.
2889 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2890 // The BitcodeStartBit was the stream offset of the identification block.
2891 VSTOffset -= bitcodeStartBit();
2892 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2893 // Note that we add 1 here because the offset is relative to one word
2894 // before the start of the identification block, which was historically
2895 // always the start of the regular bitcode header.
2896 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002897
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002898 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002899
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002900 auto Abbv = std::make_shared<BitCodeAbbrev>();
2901 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2904 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002905
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002906 for (const Function &F : M) {
2907 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002908
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002909 if (F.isDeclaration())
2910 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002911
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002912 Record[0] = VE.getValueID(&F);
2913
2914 // Save the word offset of the function (from the start of the
2915 // actual bitcode written to the stream).
2916 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2917 assert((BitcodeIndex & 31) == 0 && "function 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 Record[1] = BitcodeIndex / 32 + 1;
2922
2923 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002924 }
2925
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002926 Stream.ExitBlock();
2927}
2928
2929/// Emit names for arguments, instructions and basic blocks in a function.
2930void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2931 const ValueSymbolTable &VST) {
2932 if (VST.empty())
2933 return;
2934
2935 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2936
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002937 // FIXME: Set up the abbrev, we know how many values there are!
2938 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002939 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002940
Yaron Keren001e2e42015-08-10 07:04:29 +00002941 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002942 // Figure out the encoding to use for the name.
David Blaikieb6b42e02017-06-02 17:24:26 +00002943 StringEncoding Bits = getStringEncoding(Name.getKey());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002944
Chris Lattnera0987962007-05-04 21:31:13 +00002945 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002946 NameVals.push_back(VE.getValueID(Name.getValue()));
2947
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002948 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002949 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002950 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002951 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002952 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002953 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002954 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002955 } else {
2956 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002957 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002958 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002959 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002960 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002961 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002962
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002963 for (const auto P : Name.getKey())
2964 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002965
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002966 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002967 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002968 NameVals.clear();
2969 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002970
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002971 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002972}
2973
Teresa Johnson37687f32016-04-23 04:30:47 +00002974void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002975 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2976 unsigned Code;
2977 if (isa<BasicBlock>(Order.V))
2978 Code = bitc::USELIST_CODE_BB;
2979 else
2980 Code = bitc::USELIST_CODE_DEFAULT;
2981
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002982 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002983 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002984 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002985}
2986
Teresa Johnson37687f32016-04-23 04:30:47 +00002987void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002988 assert(VE.shouldPreserveUseListOrder() &&
2989 "Expected to be preserving use-list order");
2990
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002991 auto hasMore = [&]() {
2992 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2993 };
2994 if (!hasMore())
2995 // Nothing to do.
2996 return;
2997
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002998 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002999 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003000 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003001 VE.UseListOrders.pop_back();
3002 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003003 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003004}
3005
Teresa Johnson403a7872015-10-04 14:33:43 +00003006/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00003007void ModuleBitcodeWriter::writeFunction(
3008 const Function &F,
3009 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00003010 // Save the bitcode index of the start of this function block for recording
3011 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003012 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003013
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003014 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00003015 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003016
3017 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003018
Chris Lattnere6e364c2007-04-26 05:53:54 +00003019 // Emit the number of basic blocks, so the reader can create them ahead of
3020 // time.
3021 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003022 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003023 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003024
Chris Lattnere6e364c2007-04-26 05:53:54 +00003025 // If there are function-local constants, emit them now.
3026 unsigned CstStart, CstEnd;
3027 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00003028 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003029
Victor Hernandez6c730de2010-01-14 01:50:08 +00003030 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00003031 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00003032
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003033 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003034 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003035
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003036 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003037
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003038 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00003039 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003040 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003041 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3042 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003043 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003044
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00003045 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003046 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003047
Chris Lattner07d09ed2010-04-03 02:17:50 +00003048 // If the instruction has metadata, write a metadata attachment later.
3049 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003050
Chris Lattner07d09ed2010-04-03 02:17:50 +00003051 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003052 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003053 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003054 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003055
3056 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00003057 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003058 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003059 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003060 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003061
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003062 Vals.push_back(DL->getLine());
3063 Vals.push_back(DL->getColumn());
3064 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3065 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003066 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003067 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00003068
3069 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003070 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003071
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003072 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003073 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003074 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00003075
Chris Lattner07d09ed2010-04-03 02:17:50 +00003076 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003077 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003078 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003079 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00003080 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003081 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00003082}
3083
Chris Lattner702658c2007-05-04 18:26:27 +00003084// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003085void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00003086 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00003087 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00003088 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00003089 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003090
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003091 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003092 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3094 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3095 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3096 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003097 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003098 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003099 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003100 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003101
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003102 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003103 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003104 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3106 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003108 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003109 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003110 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003111 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003112 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003113 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00003114 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3115 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3116 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3117 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003118 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003119 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003120 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00003121 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003122 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003123 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003124 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00003127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003128 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003129 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003130 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003131 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003132
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003133 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003134 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003135 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003137 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003138 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003139 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003140 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003141 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003142
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003143 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003144 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003145 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003147 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003148 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003149 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003150 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003151
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003152 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003153 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003154 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003157 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3159
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003160 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003161 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003162 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003163 }
3164 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003165 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003166 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003167 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003168 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003169 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003170 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003171
Chris Lattnerb80751d2007-05-05 07:44:49 +00003172 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003173
Chris Lattnerb80751d2007-05-05 07:44:49 +00003174 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003175 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003176 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3179 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003182 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003183 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003184 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003185 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003186 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003187 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003188 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003192 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003193 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003194 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003195 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003196 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003197 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003198 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3200 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Steven Wu545d34a2018-02-19 19:22:28 +00003202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003203 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003204 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003205 llvm_unreachable("Unexpected abbrev ordering!");
3206 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003207 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003208 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003209 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003212 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003214 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003215 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003216 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003217 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003218
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003219 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003220 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003221 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003222 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003223 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003224 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003225 }
3226 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003227 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003228 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003230 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003231 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003232 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003233 }
3234 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003235 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003236 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003237 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003238 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003239 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003240 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003241 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003242 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003243 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3246 Log2_32_Ceil(VE.getTypes().size() + 1)));
3247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3248 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003249 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003250 FUNCTION_INST_GEP_ABBREV)
3251 llvm_unreachable("Unexpected abbrev ordering!");
3252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003253
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003254 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003255}
3256
Teresa Johnson403a7872015-10-04 14:33:43 +00003257/// Write the module path strings, currently only used when generating
3258/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003259void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003260 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003261
3262 // TODO: See which abbrev sizes we actually need to emit
3263
3264 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003265 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003266 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3267 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3268 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003270 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003271
3272 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003273 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003274 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3275 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3276 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003278 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003279
3280 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003281 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003282 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3284 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003286 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003287
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003288 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003289 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003290 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3291 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3292 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3294 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3295 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003296 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003297
3298 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003299 forEachModule(
3300 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
David Blaikieb6b42e02017-06-02 17:24:26 +00003301 StringRef Key = MPSE.getKey();
3302 const auto &Value = MPSE.getValue();
3303 StringEncoding Bits = getStringEncoding(Key);
Teresa Johnson7a27b132017-06-02 01:56:02 +00003304 unsigned AbbrevToUse = Abbrev8Bit;
3305 if (Bits == SE_Char6)
3306 AbbrevToUse = Abbrev6Bit;
3307 else if (Bits == SE_Fixed7)
3308 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003309
David Blaikieb6b42e02017-06-02 17:24:26 +00003310 Vals.push_back(Value.first);
3311 Vals.append(Key.begin(), Key.end());
Teresa Johnson403a7872015-10-04 14:33:43 +00003312
Teresa Johnson7a27b132017-06-02 01:56:02 +00003313 // Emit the finished record.
3314 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003315
Teresa Johnson7a27b132017-06-02 01:56:02 +00003316 // Emit an optional hash for the module now
David Blaikieb6b42e02017-06-02 17:24:26 +00003317 const auto &Hash = Value.second;
3318 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3319 Vals.assign(Hash.begin(), Hash.end());
Teresa Johnson7a27b132017-06-02 01:56:02 +00003320 // Emit the hash record.
3321 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3322 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003323
Teresa Johnson7a27b132017-06-02 01:56:02 +00003324 Vals.clear();
3325 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003326 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003327}
3328
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003329/// Write the function type metadata related records that need to appear before
3330/// a function summary entry (whether per-module or combined).
3331static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3332 FunctionSummary *FS) {
3333 if (!FS->type_tests().empty())
3334 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3335
3336 SmallVector<uint64_t, 64> Record;
3337
3338 auto WriteVFuncIdVec = [&](uint64_t Ty,
3339 ArrayRef<FunctionSummary::VFuncId> VFs) {
3340 if (VFs.empty())
3341 return;
3342 Record.clear();
3343 for (auto &VF : VFs) {
3344 Record.push_back(VF.GUID);
3345 Record.push_back(VF.Offset);
3346 }
3347 Stream.EmitRecord(Ty, Record);
3348 };
3349
3350 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3351 FS->type_test_assume_vcalls());
3352 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3353 FS->type_checked_load_vcalls());
3354
3355 auto WriteConstVCallVec = [&](uint64_t Ty,
3356 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3357 for (auto &VC : VCs) {
3358 Record.clear();
3359 Record.push_back(VC.VFunc.GUID);
3360 Record.push_back(VC.VFunc.Offset);
3361 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3362 Stream.EmitRecord(Ty, Record);
3363 }
3364 };
3365
3366 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3367 FS->type_test_assume_const_vcalls());
3368 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3369 FS->type_checked_load_const_vcalls());
3370}
3371
Vitaly Buka44396fa2018-02-14 22:41:15 +00003372static void writeWholeProgramDevirtResolutionByArg(
3373 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3374 const WholeProgramDevirtResolution::ByArg &ByArg) {
3375 NameVals.push_back(args.size());
3376 NameVals.insert(NameVals.end(), args.begin(), args.end());
3377
3378 NameVals.push_back(ByArg.TheKind);
3379 NameVals.push_back(ByArg.Info);
3380 NameVals.push_back(ByArg.Byte);
3381 NameVals.push_back(ByArg.Bit);
3382}
3383
3384static void writeWholeProgramDevirtResolution(
3385 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3386 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3387 NameVals.push_back(Id);
3388
3389 NameVals.push_back(Wpd.TheKind);
3390 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3391 NameVals.push_back(Wpd.SingleImplName.size());
3392
3393 NameVals.push_back(Wpd.ResByArg.size());
3394 for (auto &A : Wpd.ResByArg)
3395 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3396}
3397
3398static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3399 StringTableBuilder &StrtabBuilder,
3400 const std::string &Id,
3401 const TypeIdSummary &Summary) {
3402 NameVals.push_back(StrtabBuilder.add(Id));
3403 NameVals.push_back(Id.size());
3404
3405 NameVals.push_back(Summary.TTRes.TheKind);
3406 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3407 NameVals.push_back(Summary.TTRes.AlignLog2);
3408 NameVals.push_back(Summary.TTRes.SizeM1);
3409 NameVals.push_back(Summary.TTRes.BitMask);
3410 NameVals.push_back(Summary.TTRes.InlineBits);
3411
3412 for (auto &W : Summary.WPDRes)
3413 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3414 W.second);
3415}
3416
Teresa Johnson403a7872015-10-04 14:33:43 +00003417// Helper to emit a single function summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003418void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003419 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003420 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3421 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003422 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003423
Teresa Johnson28e457b2016-04-24 14:57:11 +00003424 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003425 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003426
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003427 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003428 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003429 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003430 NameVals.push_back(FS->refs().size());
3431
3432 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003433 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003434
Easwaran Ramana17f2202017-12-22 01:33:52 +00003435 bool HasProfileData = F.hasProfileData();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003436 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003437 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003438 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003439 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003440 else if (WriteRelBFToSummary)
3441 NameVals.push_back(ECI.second.RelBlockFreq);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003442 }
3443
3444 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3445 unsigned Code =
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003446 (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3447 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3448 : bitc::FS_PERMODULE));
Teresa Johnson403a7872015-10-04 14:33:43 +00003449
3450 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003451 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003452 NameVals.clear();
3453}
3454
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003455// Collect the global value references in the given variable's initializer,
3456// and emit them in a summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003457void ModuleBitcodeWriterBase::writeModuleLevelReferences(
Teresa Johnson37687f32016-04-23 04:30:47 +00003458 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3459 unsigned FSModRefsAbbrev) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00003460 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3461 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003462 // Only declarations should not have a summary (a declaration might however
3463 // have a summary if the def was in module level asm).
3464 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003465 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003466 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003467 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003468 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003469 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003470 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003471
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003472 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003473 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003474 NameVals.push_back(VE.getValueID(RI.getValue()));
3475 // Sort the refs for determinism output, the vector returned by FS->refs() has
3476 // been initialized from a DenseSet.
3477 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003478
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003479 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3480 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003481 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003482}
Teresa Johnson403a7872015-10-04 14:33:43 +00003483
Mehdi Amini8fe69362016-04-24 03:18:11 +00003484// Current version for the summary.
3485// This is bumped whenever we introduce changes in the way some record are
3486// interpreted, like flags for instance.
Charles Saternos75da10d2017-08-04 16:00:58 +00003487static const uint64_t INDEX_VERSION = 4;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003488
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003489/// Emit the per-module summary section alongside the rest of
3490/// the module's bitcode.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003491void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
Peter Collingbournee357fbd2017-06-08 23:01:49 +00003492 // By default we compile with ThinLTO if the module has a summary, but the
3493 // client can request full LTO with a module flag.
3494 bool IsThinLTO = true;
3495 if (auto *MD =
3496 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3497 IsThinLTO = MD->getZExtValue();
3498 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3499 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3500 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003501
Mehdi Amini8fe69362016-04-24 03:18:11 +00003502 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3503
Teresa Johnson620c1402016-09-20 23:07:17 +00003504 if (Index->begin() == Index->end()) {
3505 Stream.ExitBlock();
3506 return;
3507 }
3508
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003509 for (const auto &GVI : valueIds()) {
3510 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3511 ArrayRef<uint64_t>{GVI.second, GVI.first});
3512 }
3513
Easwaran Ramanbf38dee2018-01-24 18:15:29 +00003514 // Abbrev for FS_PERMODULE_PROFILE.
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003515 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003516 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3517 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003518 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003519 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003520 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003522 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003525 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003526
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003527 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3528 Abbv = std::make_shared<BitCodeAbbrev>();
3529 if (WriteRelBFToSummary)
3530 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3531 else
3532 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3533 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3534 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3535 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3536 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3538 // numrefs x valueid, n x (valueid [, rel_block_freq])
3539 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3540 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3541 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3542
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003543 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003544 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003545 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3546 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3549 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003550 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003551
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003552 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003553 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003554 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3555 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003556 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003557 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003558 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003559
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003560 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003561 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003562 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003563 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003564 // Summary emission does not support anonymous functions, they have to
3565 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003566 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003567 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003568
Peter Collingbourne9667b912017-05-04 18:03:25 +00003569 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3570 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003571 // Only declarations should not have a summary (a declaration might
3572 // however have a summary if the def was in module level asm).
3573 assert(F.isDeclaration());
3574 continue;
3575 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003576 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003577 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3578 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003579 }
3580
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003581 // Capture references from GlobalVariable initializers, which are outside
3582 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003583 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003584 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003585
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003586 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003587 auto *Aliasee = A.getBaseObject();
3588 if (!Aliasee->hasName())
3589 // Nameless function don't have an entry in the summary, skip it.
3590 continue;
3591 auto AliasId = VE.getValueID(&A);
3592 auto AliaseeId = VE.getValueID(Aliasee);
3593 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003594 auto *Summary = Index->getGlobalValueSummary(A);
3595 AliasSummary *AS = cast<AliasSummary>(Summary);
3596 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003597 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003598 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003599 NameVals.clear();
3600 }
3601
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003602 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003603}
3604
Teresa Johnson26ab5772016-03-15 00:04:37 +00003605/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003606void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003607 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003608 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003609
Vitaly Buka769134d2018-02-16 23:38:22 +00003610 // Write the index flags.
3611 uint64_t Flags = 0;
3612 if (Index.withGlobalValueDeadStripping())
3613 Flags |= 0x1;
3614 if (Index.skipModuleByDistributedBackend())
3615 Flags |= 0x2;
3616 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
Teresa Johnsonf3681012018-02-07 04:05:59 +00003617
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003618 for (const auto &GVI : valueIds()) {
3619 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3620 ArrayRef<uint64_t>{GVI.second, GVI.first});
3621 }
3622
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003623 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003624 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003625 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003626 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003627 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003628 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003629 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003632 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003635 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003636
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003637 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003638 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003639 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003640 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003641 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003642 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003643 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003644 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003646 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003649 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003650
3651 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003652 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003653 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003654 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003655 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003656 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003659 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003660
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003661 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003662 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003663 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003664 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003665 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003668 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003669
Teresa Johnson02e98332016-04-27 13:28:35 +00003670 // The aliases are emitted as a post-pass, and will point to the value
3671 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003672 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003673
Teresa Johnson02e98332016-04-27 13:28:35 +00003674 // Save the value id for each summary for alias emission.
3675 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3676
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003677 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003678
3679 // For local linkage, we also emit the original name separately
3680 // immediately after the record.
3681 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3682 if (!GlobalValue::isLocalLinkage(S.linkage()))
3683 return;
3684 NameVals.push_back(S.getOriginalName());
3685 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3686 NameVals.clear();
3687 };
3688
Teresa Johnson81bbf742017-12-16 00:18:12 +00003689 forEachSummary([&](GVInfo I, bool IsAliasee) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003690 GlobalValueSummary *S = I.second;
3691 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003692
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003693 auto ValueId = getValueId(I.first);
3694 assert(ValueId);
3695 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003696
Teresa Johnson81bbf742017-12-16 00:18:12 +00003697 // If this is invoked for an aliasee, we want to record the above
3698 // mapping, but then not emit a summary entry (if the aliasee is
3699 // to be imported, we will invoke this separately with IsAliasee=false).
3700 if (IsAliasee)
3701 return;
3702
Teresa Johnson84174c32016-05-10 13:48:23 +00003703 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3704 // Will process aliases as a post-pass because the reader wants all
3705 // global to be loaded first.
3706 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003707 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003708 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003709
Teresa Johnson84174c32016-05-10 13:48:23 +00003710 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003711 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003712 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3713 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3714 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003715 auto RefValueId = getValueId(RI.getGUID());
3716 if (!RefValueId)
3717 continue;
3718 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003719 }
3720
Teresa Johnson403a7872015-10-04 14:33:43 +00003721 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003722 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3723 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003724 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003725 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003726 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003727 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003728
3729 auto *FS = cast<FunctionSummary>(S);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003730 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003731
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003732 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003733 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3734 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3735 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003736 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003737 // Fill in below
3738 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003739
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003740 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003741 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003742 auto RefValueId = getValueId(RI.getGUID());
3743 if (!RefValueId)
3744 continue;
3745 NameVals.push_back(*RefValueId);
3746 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003747 }
Charles Saternos75da10d2017-08-04 16:00:58 +00003748 NameVals[5] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003749
3750 bool HasProfileData = false;
3751 for (auto &EI : FS->calls()) {
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003752 HasProfileData |=
3753 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003754 if (HasProfileData)
3755 break;
3756 }
3757
3758 for (auto &EI : FS->calls()) {
3759 // If this GUID doesn't have a value id, it doesn't have a function
3760 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003761 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003762 auto CallValueId = getValueId(GUID);
3763 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003764 // For SamplePGO, the indirect call targets for local functions will
3765 // have its original name annotated in profile. We try to find the
3766 // corresponding PGOFuncName as the GUID.
3767 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003768 if (GUID == 0)
3769 continue;
3770 CallValueId = getValueId(GUID);
3771 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003772 continue;
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003773 // The mapping from OriginalId to GUID may return a GUID
Xinliang David Li5a57b842017-08-16 17:33:43 +00003774 // that corresponds to a static variable. Filter it out here.
3775 // This can happen when
3776 // 1) There is a call to a library function which does not have
3777 // a CallValidId;
3778 // 2) There is a static variable with the OriginalGUID identical
3779 // to the GUID of the library function in 1);
3780 // When this happens, the logic for SamplePGO kicks in and
Mandeep Singh Grang1be19e62017-09-15 20:01:43 +00003781 // the static variable in 2) will be found, which needs to be
Xinliang David Li5a57b842017-08-16 17:33:43 +00003782 // filtered out.
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003783 auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3784 if (GVSum &&
3785 GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3786 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +00003787 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003788 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003789 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003790 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003791 }
3792
3793 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3794 unsigned Code =
3795 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3796
3797 // Emit the finished record.
3798 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3799 NameVals.clear();
3800 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003801 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003802
Teresa Johnson28e457b2016-04-24 14:57:11 +00003803 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003804 auto AliasValueId = SummaryToValueIdMap[AS];
3805 assert(AliasValueId);
3806 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003807 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003808 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003809 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3810 assert(AliaseeValueId);
3811 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003812
3813 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003814 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003815 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003816 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003817 }
3818
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003819 if (!Index.cfiFunctionDefs().empty()) {
3820 for (auto &S : Index.cfiFunctionDefs()) {
3821 NameVals.push_back(StrtabBuilder.add(S));
3822 NameVals.push_back(S.size());
3823 }
3824 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3825 NameVals.clear();
3826 }
3827
3828 if (!Index.cfiFunctionDecls().empty()) {
3829 for (auto &S : Index.cfiFunctionDecls()) {
3830 NameVals.push_back(StrtabBuilder.add(S));
3831 NameVals.push_back(S.size());
3832 }
3833 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3834 NameVals.clear();
3835 }
3836
Vitaly Buka44396fa2018-02-14 22:41:15 +00003837 if (!Index.typeIds().empty()) {
3838 for (auto &S : Index.typeIds()) {
3839 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, S.first, S.second);
3840 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
3841 NameVals.clear();
3842 }
3843 }
3844
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003845 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003846}
3847
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003848/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3849/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003850static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003851 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003852
3853 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003854 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003855 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3857 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003858 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003859 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003860 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003861
3862 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003863 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003864 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003866 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003867 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003868 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3869 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003870}
3871
Teresa Johnson37687f32016-04-23 04:30:47 +00003872void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003873 // Emit the module's hash.
3874 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003875 if (GenerateHash) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003876 uint32_t Vals[5];
3877 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3878 Buffer.size() - BlockStartPos));
3879 StringRef Hash = Hasher.result();
3880 for (int Pos = 0; Pos < 20; Pos += 4) {
3881 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3882 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003883
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003884 // Emit the finished record.
3885 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3886
3887 if (ModHash)
3888 // Save the written hash value.
3889 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
Haojie Wang1dec57d2017-07-21 17:25:20 +00003890 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003891}
3892
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003893void ModuleBitcodeWriter::write() {
3894 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003895
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003896 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3897 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003898
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003899 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003900
3901 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003902 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003903
Bill Wendlingdc095552013-02-10 23:09:32 +00003904 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003905 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003906
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003907 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003908 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003909
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003910 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003911 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003912
Teresa Johnson37687f32016-04-23 04:30:47 +00003913 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003914
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003915 // Emit top-level description of module, including target triple, inline asm,
3916 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003917 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003918
Devang Patele059ba6e2009-07-23 01:07:34 +00003919 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003920 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003921
Peter Collingbourne21521892016-06-21 23:42:48 +00003922 // Emit metadata kind names.
3923 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003924
Devang Patelaf206b82009-09-18 19:26:43 +00003925 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003926 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003927
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003928 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003929 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003930 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003931
Teresa Johnson37687f32016-04-23 04:30:47 +00003932 writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003933 writeSyncScopeNames();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003934
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003935 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003936 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003937 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003938 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003939 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003940
3941 // Need to write after the above call to WriteFunction which populates
3942 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003943 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003944 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003945
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003946 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003947
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003948 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003949
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003950 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003951}
3952
Teresa Johnson37687f32016-04-23 04:30:47 +00003953static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3954 uint32_t &Position) {
3955 support::endian::write32le(&Buffer[Position], Value);
3956 Position += 4;
3957}
3958
3959/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003960/// header and trailer to make it compatible with the system archiver. To do
3961/// this we emit the following header, and then emit a trailer that pads the
3962/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003963///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003964/// struct bc_header {
3965/// uint32_t Magic; // 0x0B17C0DE
3966/// uint32_t Version; // Version, currently always 0.
3967/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3968/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3969/// uint32_t CPUType; // CPU specifier.
3970/// ... potentially more later ...
3971/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003972static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003973 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003974 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003975
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003976 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003977 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3978 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3979 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003980 enum {
3981 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3982 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003983 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003984 DARWIN_CPU_TYPE_POWERPC = 18
3985 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003986
Evan Chengcffdcae2011-06-14 01:51:33 +00003987 Triple::ArchType Arch = TT.getArch();
3988 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003989 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003990 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003991 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003992 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003993 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003994 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003995 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003996 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003997 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003998
Chris Lattnera660f4b2008-07-09 05:14:23 +00003999 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004000 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004001 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004002 unsigned BCOffset = BWH_HeaderSize;
4003 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004004
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004005 // Write the magic and version.
4006 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00004007 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4008 writeInt32ToBuffer(0, Buffer, Position); // Version.
4009 writeInt32ToBuffer(BCOffset, Buffer, Position);
4010 writeInt32ToBuffer(BCSize, Buffer, Position);
4011 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004012
Chris Lattnera660f4b2008-07-09 05:14:23 +00004013 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004014 while (Buffer.size() & 15)
4015 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00004016}
4017
Teresa Johnson403a7872015-10-04 14:33:43 +00004018/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004019static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004020 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004021 Stream.Emit((unsigned)'B', 8);
4022 Stream.Emit((unsigned)'C', 8);
4023 Stream.Emit(0x0, 4);
4024 Stream.Emit(0xC, 4);
4025 Stream.Emit(0xE, 4);
4026 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00004027}
4028
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004029BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4030 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4031 writeBitcodeHeader(*Stream);
4032}
4033
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004034BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4035
4036void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4037 Stream->EnterSubblock(Block, 3);
4038
4039 auto Abbv = std::make_shared<BitCodeAbbrev>();
4040 Abbv->Add(BitCodeAbbrevOp(Record));
4041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4042 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4043
4044 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4045
4046 Stream->ExitBlock();
4047}
4048
Peter Collingbourne92648c22017-06-27 23:50:11 +00004049void BitcodeWriter::writeSymtab() {
4050 assert(!WroteStrtab && !WroteSymtab);
4051
4052 // If any module has module-level inline asm, we will require a registered asm
4053 // parser for the target so that we can create an accurate symbol table for
4054 // the module.
4055 for (Module *M : Mods) {
4056 if (M->getModuleInlineAsm().empty())
4057 continue;
4058
4059 std::string Err;
4060 const Triple TT(M->getTargetTriple());
4061 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4062 if (!T || !T->hasMCAsmParser())
4063 return;
4064 }
4065
4066 WroteSymtab = true;
4067 SmallVector<char, 0> Symtab;
4068 // The irsymtab::build function may be unable to create a symbol table if the
4069 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4070 // table is not required for correctness, but we still want to be able to
4071 // write malformed modules to bitcode files, so swallow the error.
4072 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4073 consumeError(std::move(E));
4074 return;
4075 }
4076
4077 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4078 {Symtab.data(), Symtab.size()});
4079}
4080
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004081void BitcodeWriter::writeStrtab() {
4082 assert(!WroteStrtab);
4083
4084 std::vector<char> Strtab;
4085 StrtabBuilder.finalizeInOrder();
4086 Strtab.resize(StrtabBuilder.getSize());
4087 StrtabBuilder.write((uint8_t *)Strtab.data());
4088
4089 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4090 {Strtab.data(), Strtab.size()});
4091
4092 WroteStrtab = true;
4093}
4094
4095void BitcodeWriter::copyStrtab(StringRef Strtab) {
4096 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4097 WroteStrtab = true;
4098}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004099
Rafael Espindola6a86e252018-02-14 19:11:32 +00004100void BitcodeWriter::writeModule(const Module &M,
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004101 bool ShouldPreserveUseListOrder,
4102 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004103 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbourne92648c22017-06-27 23:50:11 +00004104 assert(!WroteStrtab);
4105
4106 // The Mods vector is used by irsymtab::build, which requires non-const
4107 // Modules in case it needs to materialize metadata. But the bitcode writer
4108 // requires that the module is materialized, so we can cast to non-const here,
4109 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004110 assert(M.isMaterialized());
4111 Mods.push_back(const_cast<Module *>(&M));
Peter Collingbourne92648c22017-06-27 23:50:11 +00004112
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004113 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004114 ShouldPreserveUseListOrder, Index,
4115 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004116 ModuleWriter.write();
4117}
4118
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004119void BitcodeWriter::writeIndex(
4120 const ModuleSummaryIndex *Index,
4121 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4122 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4123 ModuleToSummariesForIndex);
4124 IndexWriter.write();
4125}
4126
Rafael Espindola6a86e252018-02-14 19:11:32 +00004127/// Write the specified module to the specified output stream.
4128void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00004129 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004130 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004131 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00004132 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00004133 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004134
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004135 // If this is darwin or another generic macho target, reserve space for the
4136 // header.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004137 Triple TT(M.getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00004138 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004139 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004140
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004141 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004142 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4143 ModHash);
Peter Collingbourne92648c22017-06-27 23:50:11 +00004144 Writer.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004145 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004146
Akira Hatanaka1235d282016-01-23 16:02:10 +00004147 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00004148 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004149
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004150 // Write the generated bitstream to "Out".
4151 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004152}
Teresa Johnson403a7872015-10-04 14:33:43 +00004153
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004154void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004155 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00004156
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004157 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00004158
4159 // Write the module paths in the combined index.
4160 writeModStrings();
4161
4162 // Write the summary combined index records.
4163 writeCombinedGlobalValueSummary();
4164
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004165 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00004166}
4167
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004168// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00004169// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00004170// writing the combined index file for ThinLTO. When writing a subset of the
4171// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4172void llvm::WriteIndexToFile(
4173 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00004174 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004175 SmallVector<char, 0> Buffer;
4176 Buffer.reserve(256 * 1024);
4177
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004178 BitcodeWriter Writer(Buffer);
4179 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4180 Writer.writeStrtab();
Teresa Johnson403a7872015-10-04 14:33:43 +00004181
4182 Out.write((char *)&Buffer.front(), Buffer.size());
4183}
Haojie Wang1dec57d2017-07-21 17:25:20 +00004184
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00004185namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +00004186
Haojie Wang1dec57d2017-07-21 17:25:20 +00004187/// Class to manage the bitcode writing for a thin link bitcode file.
4188class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4189 /// ModHash is for use in ThinLTO incremental build, generated while writing
4190 /// the module bitcode file.
4191 const ModuleHash *ModHash;
4192
4193public:
Rafael Espindola6a86e252018-02-14 19:11:32 +00004194 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004195 BitstreamWriter &Stream,
4196 const ModuleSummaryIndex &Index,
4197 const ModuleHash &ModHash)
4198 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4199 /*ShouldPreserveUseListOrder=*/false, &Index),
4200 ModHash(&ModHash) {}
4201
4202 void write();
4203
4204private:
4205 void writeSimplifiedModuleInfo();
4206};
Eugene Zelenko975293f2017-09-07 23:28:24 +00004207
4208} // end anonymous namespace
Haojie Wang1dec57d2017-07-21 17:25:20 +00004209
4210// This function writes a simpilified module info for thin link bitcode file.
4211// It only contains the source file name along with the name(the offset and
4212// size in strtab) and linkage for global values. For the global value info
4213// entry, in order to keep linkage at offset 5, there are three zeros used
4214// as padding.
4215void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4216 SmallVector<unsigned, 64> Vals;
4217 // Emit the module's source file name.
4218 {
4219 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4220 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4221 if (Bits == SE_Char6)
4222 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4223 else if (Bits == SE_Fixed7)
4224 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4225
4226 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4227 auto Abbv = std::make_shared<BitCodeAbbrev>();
4228 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4229 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4230 Abbv->Add(AbbrevOpToUse);
4231 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4232
4233 for (const auto P : M.getSourceFileName())
4234 Vals.push_back((unsigned char)P);
4235
4236 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4237 Vals.clear();
4238 }
4239
4240 // Emit the global variable information.
4241 for (const GlobalVariable &GV : M.globals()) {
4242 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4243 Vals.push_back(StrtabBuilder.add(GV.getName()));
4244 Vals.push_back(GV.getName().size());
4245 Vals.push_back(0);
4246 Vals.push_back(0);
4247 Vals.push_back(0);
4248 Vals.push_back(getEncodedLinkage(GV));
4249
4250 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4251 Vals.clear();
4252 }
4253
4254 // Emit the function proto information.
4255 for (const Function &F : M) {
4256 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4257 Vals.push_back(StrtabBuilder.add(F.getName()));
4258 Vals.push_back(F.getName().size());
4259 Vals.push_back(0);
4260 Vals.push_back(0);
4261 Vals.push_back(0);
4262 Vals.push_back(getEncodedLinkage(F));
4263
4264 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4265 Vals.clear();
4266 }
4267
4268 // Emit the alias information.
4269 for (const GlobalAlias &A : M.aliases()) {
4270 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4271 Vals.push_back(StrtabBuilder.add(A.getName()));
4272 Vals.push_back(A.getName().size());
4273 Vals.push_back(0);
4274 Vals.push_back(0);
4275 Vals.push_back(0);
4276 Vals.push_back(getEncodedLinkage(A));
4277
4278 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4279 Vals.clear();
4280 }
4281
4282 // Emit the ifunc information.
4283 for (const GlobalIFunc &I : M.ifuncs()) {
4284 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4285 Vals.push_back(StrtabBuilder.add(I.getName()));
4286 Vals.push_back(I.getName().size());
4287 Vals.push_back(0);
4288 Vals.push_back(0);
4289 Vals.push_back(0);
4290 Vals.push_back(getEncodedLinkage(I));
4291
4292 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4293 Vals.clear();
4294 }
4295}
4296
4297void ThinLinkBitcodeWriter::write() {
4298 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4299
4300 writeModuleVersion();
4301
4302 writeSimplifiedModuleInfo();
4303
4304 writePerModuleGlobalValueSummary();
4305
4306 // Write module hash.
4307 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4308
4309 Stream.ExitBlock();
4310}
4311
Rafael Espindola6a86e252018-02-14 19:11:32 +00004312void BitcodeWriter::writeThinLinkBitcode(const Module &M,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004313 const ModuleSummaryIndex &Index,
4314 const ModuleHash &ModHash) {
4315 assert(!WroteStrtab);
4316
4317 // The Mods vector is used by irsymtab::build, which requires non-const
4318 // Modules in case it needs to materialize metadata. But the bitcode writer
4319 // requires that the module is materialized, so we can cast to non-const here,
4320 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004321 assert(M.isMaterialized());
4322 Mods.push_back(const_cast<Module *>(&M));
Haojie Wang1dec57d2017-07-21 17:25:20 +00004323
4324 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4325 ModHash);
4326 ThinLinkWriter.write();
4327}
4328
4329// Write the specified thin link bitcode file to the given raw output stream,
4330// where it will be written in a new bitcode block. This is used when
4331// writing the per-module index file for ThinLTO.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004332void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004333 const ModuleSummaryIndex &Index,
4334 const ModuleHash &ModHash) {
4335 SmallVector<char, 0> Buffer;
4336 Buffer.reserve(256 * 1024);
4337
4338 BitcodeWriter Writer(Buffer);
4339 Writer.writeThinLinkBitcode(M, Index, ModHash);
4340 Writer.writeSymtab();
4341 Writer.writeStrtab();
4342
4343 Out.write((char *)&Buffer.front(), Buffer.size());
4344}